<?php
include('dbconnect.php');
if (empty($_SESSION['user_id']) || empty($_SESSION['role'])) {
    header("Location: auth-signin.php");
    exit();
}

include('function.php');
include('header.php');

?>

        <!-- ==================================================== -->
        <!-- Start right Content here -->
        <!-- ==================================================== -->
<style>

.checkbox-container {
  display: flex;
  justify-content: space-between;  /* This will space out the label and checkbox to opposite ends */
  align-items: center;  /* Vertically centers the label and checkbox */
}

.mb-3 {
  width: 100%;  /* Ensures that the container takes the full width */
}

.search-container {
  display: flex;
  align-items: center;
  border: 1px solid #ccc;
  border-radius: 20px;
  padding: 5px;
  max-width: 300px;
}

.search-box {
  border: none;
  outline: none;
  padding: 8px;
  width: 100%;
  border-radius: 20px;
}

.search-btn {
  background-color: transparent;
  border: none;
  cursor: pointer;
  padding: 8px;
  color: #333;
}

.search-btn i {
  font-size: 18px;  /* Size of the search icon */
}

/* Container for all dropdowns */
.dropdown-container {
  display: flex;
  justify-content: flex-start;
  gap: 20px;  /* Optional: Adds space between each dropdown */
  flex-wrap: wrap;  /* Allows the dropdowns to wrap to the next line if needed */
}



</style>

<script>
//document.getElementById('basic-datepicker').flatpickr();
</script>
<script>
let assignedUserChoices = null; // Declare this outside the function, globally

function getassigneduseronchngprj() {
    console.log("Function triggered");
    const projectSelect = document.getElementById("project_select");
    const assignedUserSelect = document.getElementById("assigned_user");

    if (!projectSelect || !assignedUserSelect) {
        console.error("One or both select elements not found!");
        return;
    }

    const selectedOptions = Array.from(projectSelect.selectedOptions).map(opt => opt.value);

    if (selectedOptions.length === 0) {
        assignedUserSelect.innerHTML = '<option value="">Select Assigned User</option>';
        if (assignedUserChoices) {
            assignedUserChoices.destroy();
            assignedUserChoices = new Choices(assignedUserSelect, { shouldSort: false });
        }
        return;
    }

    const xhr = new XMLHttpRequest();
    xhr.open("POST", "get-assigned-users.php", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xhr.onload = function () {
        if (xhr.status === 200) {
            // Destroy existing Choices instance if it exists
            if (assignedUserChoices) {
                assignedUserChoices.destroy();
            }

            // Update options
            assignedUserSelect.innerHTML = xhr.responseText;

            // Re-initialize Choices.js
            assignedUserChoices = new Choices(assignedUserSelect, { shouldSort: false });
        } else {
            alert("Failed to load users");
        }
    };

    const params = "project_ids[]=" + selectedOptions.join("&project_ids[]=");
    xhr.send(params);
}


</script>

<script>
document.addEventListener("DOMContentLoaded", function () {
    const now = new Date();

    const yyyy = now.getFullYear();
    const mm = String(now.getMonth() + 1).padStart(2, '0');
    const dd = String(now.getDate()).padStart(2, '0');
    const todayStr = `${yyyy}-${mm}-${dd}`;
    const currentTime = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;

    // Get all date inputs
    const dateInputs = document.querySelectorAll('.date-input');

    dateInputs.forEach(dateInput => {
        const timeInput = dateInput.nextElementSibling; // Assumes time input is right after date

        if (!timeInput || !timeInput.classList.contains('time-input')) return;

        // Set min date
        dateInput.min = todayStr;

        // Optional: set default value
        dateInput.value = todayStr;
        timeInput.value = currentTime;

        // Add change event to update time restriction
        dateInput.addEventListener('change', function () {
            if (dateInput.value === todayStr) {
                timeInput.min = currentTime;
            } else {
                timeInput.removeAttribute('min');
            }
        });
    });
});
</script>



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">


        <div class="page-content">

            <!-- Start Container Fluid -->
            <div class="container-fluid">

                <!-- ========== Page Title Start ========== -->
				<div class="row">
                         <div class="col-lg-12">
                              <div class="card">
                                   <div class="card-header border-0">
                                        <div class="row justify-content-between">
                                             <div class="col-lg-6">
                                                  <div class="row align-items-center">
                                                       <div class="col-lg-6">
                                                        <h3 style="display: inline-block; margin-right: 10px;"><b>Leads Manager</b></h3><p style="display: inline-block;">Last Updated: <?php print date('y-m-d');  ?></p>   
                                                       </div>
                                                       <!--div class="col-lg-4">
                                                            <h5 class="text-dark fw-medium mb-0">311 <span class="text-muted"> Agent</span></h5>
                                                       </div-->
                                                  </div>
                                             </div>
                                            <?php
                                            if($_SESSION['role']=='ADMIN'){
                                            ?>
                                             <div class="col-lg-6">
                                                  <div class="text-md-end mt-3 mt-md-0">
                                                       <!--button type="button" class="btn btn-outline-primary me-1"><i class="ri-settings-2-line me-1"></i>More Setting</button-->
                                                       <!--button type="button" class="btn btn-outline-primary me-1"><i class="ri-filter-line me-1"></i> Filters</button-->
													   
                                                       <button type="button" class="btn btn-success me-1 dropdown-toggle arrow-none text-dark show" data-bs-toggle="dropdown" aria-expanded="true"><i class="ri-add-line"></i></button>
													   <div class="dropdown-menu dropdown-menu-end"><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">New Lead</a>
													   <a class="dropdown-item" href="javascript: void(0);" id="openReassignCanvas" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas12" aria-controls="rightOffcanvas">Re-assign Leads to User </a>
													   <a class="dropdown-item" href="javascript: void(0);" id="openDeleteCanvas" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas12" aria-controls="rightOffcanvas">Delete Leads</a></div>
										
                                                  </div>
                                             </div><!-- end col-->
                                              
                                            <?php
                                            }
                                            ?>
                                           
                                        </div>
                                   </div>
                              </div>
                         </div>
                    </div>
                
                <div id="confirmReassignContainer" class="mt-2 text-end" style="display: none;">
                    <button type="button" class="btn btn-primary" id="confirmReassignBtn">Confirm Reassign</button>
                </div>
                
                <div id="confirmDeleteContainer" class="mt-2 text-end" style="display: none;">
                    <button type="button" class="btn btn-primary" id="confirmDeleteBtn">Confirm Delete</button>
                </div>
                
                <div class="row">
                    <div class="col-12">
                        <!--div class="page-title-box">
                            <h4 class="mb-0 fw-semibold">Users</h4>
                            <ol class="breadcrumb mb-0">
                                <li class="breadcrumb-item"><a href="javascript: void(0);">Users</a></li>
                                <li class="breadcrumb-item active">List</li>
                            </ol>
                        </div-->
						<div class="dropdown-container">
							<div class="dropdown">
								<button class="btn btn-success dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" id="projectsButton">
                                  Projects <span id="selectedProjectsCount" class="badge bg-light text-dark ms-1" style="display: none;">0</span>
                                </button>
								<form class="dropdown-menu dropdown-lg p-3" id="projectFilterForm">
									<div class="mb-3">
										<button type="button" class="btn btn-link" id="selectAllProjects">Select All</button>
										<button type="button" class="btn btn-link" id="clearAllProjects">Clear All</button>
									</div>
									<div class="mb-3 search-container">
										<input type="text" class="search-box" id="projectSearch" placeholder="Search projects...">
										<button type="button" class="search-btn">
											<i class="fa fa-search"></i>
										</button>
									</div>
									<div id="projectCheckboxes" class="mb-3">
										<!-- Project checkboxes will be loaded here dynamically -->
									</div>
									<button type="button" class="btn btn-primary" id="applyProjectFilter">Apply Filters</button>
								</form>
							</div>
							
							<div class="dropdown">
								<button class="btn btn-success dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
									Assigned To <span id="selectedAssignedToCount" class="badge bg-light text-dark ms-1" style="display: none;">0</span>
								</button>
								<form class="dropdown-menu dropdown-lg p-3" id="assignedUserFilterForm">
									<div class="mb-3">
									<button type="button" class="btn btn-link" id="selectAllAssignedUser">Select All</button>
									<button type="button" class="btn btn-link" id="clearAllAssignedUser">Clear All</button>
								  </div>
									<div class="mb-3 search-container">
									  <input type="text" class="search-box" id="assignedUserSearch" placeholder="Search...">
									  <button type="submit" class="search-btn">
										<i class="fa fa-search"></i>  <!-- Font Awesome search icon -->
									  </button>
									</div>
									<div class="mb-3" id="assignedUserCheckboxes">
									  <!--label class="form-check-label" for="dropdownCheck">Unassigned</label>
									  <input type="checkbox" class="form-check-input" id="dropdownCheck"-->
									  <!-- Assigned user checkboxes will be loaded here dynamically -->
									</div>
									<button type="button" class="btn btn-primary" id="applyAssignedUserFilter">Apply Filters</button>
								</form>
							</div>
							
							<div class="dropdown">
								<button class="btn btn-success dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
									Created Date
								</button>
								<!-- Date Filter Form -->
                                <form class="dropdown-menu dropdown-lg p-3" id="dateFilterForm">
                                  <div class="mb-3">
                                    <button type="button" class="btn btn-link" id="clearCreatedDate">Clear All</button>
                                  </div>
                                
                                  <div class="mb-3 checkbox-container">
                                    <input type="text" id="basic-datepicker-start" class="form-control" placeholder="Start Date">
                                    &nbsp;&nbsp;
                                    <input type="text" id="basic-datepicker-end" class="form-control" placeholder="End Date">
                                  </div>
                                
                                  <!-- Radio group for preset date filters -->
                                  <div class="mb-3 checkbox-container">
                                    <label class="form-check-label" for="dateToday">Today</label>
                                    <input type="radio" name="dateFilter" class="form-check-input" id="dateToday" value="today">
                                  </div>
                                
                                  <div class="mb-3 checkbox-container">
                                    <label class="form-check-label" for="dateYesterday">Yesterday</label>
                                    <input type="radio" name="dateFilter" class="form-check-input" id="dateYesterday" value="yesterday">
                                  </div>
                                
                                  <div class="mb-3 checkbox-container">
                                    <label class="form-check-label" for="dateThisWeek">This Week</label>
                                    <input type="radio" name="dateFilter" class="form-check-input" id="dateThisWeek" value="this_week">
                                  </div>
                                
                                  <div class="mb-3 checkbox-container">
                                    <label class="form-check-label" for="dateThisMonth">This Month</label>
                                    <input type="radio" name="dateFilter" class="form-check-input" id="dateThisMonth" value="this_month">
                                  </div>
                                
                                  <button type="button" class="btn btn-primary" id="applyCreatedDateFilter">Apply Filters</button>
                                </form>

							</div>
								<div class="dropdown">
    								<button class="btn btn-success dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" id="projectsButton">
                                      Status Project <span id="selectedStatusProjectsCount" class="badge bg-light text-dark ms-1" style="display: none;">0</span>
                                    </button>
    								<form class="dropdown-menu dropdown-lg p-3" id="statusProjectFilterForm">
    									<div class="mb-3">
    										<button type="button" class="btn btn-link" id="selectAllStatusProjects">Select All</button>
    										<button type="button" class="btn btn-link" id="clearAllStatusProjects">Clear All</button>
    									</div>
    									<div class="mb-3 search-container">
    										<input type="text" class="search-box" id="statusProjectSearch" placeholder="Search projects...">
    										<button type="button" class="search-btn">
    											<i class="fa fa-search"></i>
    										</button>
    									</div>
    									<div id="statusProjectCheckboxes" class="mb-3">
    										<!-- Project checkboxes will be loaded here dynamically -->
    									</div>
    									<button type="button" class="btn btn-primary" id="applyStatusProjectFilter">Apply Filters</button>
    								</form>
							</div>
						</div>
						
                    </div>
                </div>
                <!-- ========== Page Title End ========== -->
				
					<!-- right offcanvas new lead -->
					<div class="offcanvas offcanvas-end" tabindex="-1" id="rightOffcanvas" aria-labelledby="rightOffcanvasLabel">
						<div class="offcanvas-header">
							<h4 class="offcanvas-title mt-0" id="rightOffcanvasLabel">Create New Lead</h4>
							<button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
						</div>
						<div class="offcanvas-body">
							<form class="row g-3" name="leadForm" action="#" method="POST" onsubmit="return validateForm()" enctype="multipart/form-data">
								<div class="col-md-12">
									<label for="validationDefault01" class="form-label">Lead Name</label>
									<input type="text" name="lead_name" id="lead_name" class="form-control"  placeholder="e.g. Ravi Gupta">
									
								</div>
								<div class="col-md-12">
									<label for="validationDefault02" class="form-label">Mobile No.</label>
									<input type="text" class="form-control" name="lead_mobile" id="lead_mobile"
                                       minlength="10" maxlength="15"
                                       pattern="^\+?\d{10,14}$"
                                       title="Enter a valid mobile number (with or without country code, e.g., +911234567890)">
								</div>
								<div class="col-md-12">
									<label for="validationDefault02" class="form-label">Alt. Mobile No.</label>
									<input type="text" class="form-control" name="alt_lead_mobile" id="alt_lead_mobile"
                                       minlength="10" maxlength="15"
                                       pattern="^\+?\d{10,14}$"
                                       title="Enter a valid mobile number (with or without country code, e.g., +911234567890)">
								</div>
								<div class="col-md-12">
									<label for="validationDefault02" class="form-label">Email Id(optional)</label>
									<input type="text" class="form-control" name="lead_email" id="lead_email"  placeholder="e.g. ravi@gmail.com" >
								</div>
								<div class="col-md-12">
								<label for="validationDefault02" class="form-label">Lead Source</label>
									<select class="form-control" id="choices-single-no-sorting" name="lead_source" id="lead_source" data-choices data-choices-sorting-false>
									<option value="">Select Source</option>
									<?php
									$sql=mysqli_query($conn,"Select tbl_lead_source_id,source_name from tbl_lead_source where 1 and flag=0");
									while($row = mysqli_fetch_array($sql)){
									?>
									<option value="<?=$row['tbl_lead_source_id'];?>"><?=$row['source_name'];?></option>
									<?Php 
									}
									?>
									</select>

								</div>
								<div class="col-md-12">
								<label for="validationDefault02" class="form-label">Project Name</label>
									<select class="form-control"  id="project_select" data-choices data-choices-removeItem name="project_name[]" onchange="getassigneduseronchngprj()" multiple>
										 <option value="" >Select Project</option>
										 <?php
										 $sql=mysqli_query($conn,"Select tbl_project_id,tbl_project_name from tbl_project where 1 and tbl_project_flag=0");
										 while($row = mysqli_fetch_array($sql)){
										 ?>
										 <option value="<?=$row['tbl_project_id'];?>"><?=$row['tbl_project_name'];?></option>
										 <?php 
										 }
										 ?>
									</select>


								</div>
								<div class="col-md-12">
								<label for="validationDefault02" class="form-label">Assigned User</label>
									<!--select class="form-control"  name="assigned_user" id="assigned_user" data-choices data-choices-sorting-false-->
									<select class="form-control" name="assigned_user" id="assigned_user">
										<option value="">Select Assigned User</option>
										<?php
										 $sql=mysqli_query($conn,"Select id,name from tbl_invite_user where 1 and flag=0");
										 while($row = mysqli_fetch_array($sql)){
										 ?>
										 <option value="<?=$row['id'];?>"><?=$row['name'];?></option>
										 <?php 
										 }
										 ?>
									</select>

								</div>
								<div class="col-md-12">
								<label for="validationDefault02" class="form-label">City</label>
									<select class="form-control" id="choices-single-no-sorting" name="city" data-choices data-choices-sorting-false>
										 <option value="">Select City</option>
										 <?php
										 $sql=mysqli_query($conn,"Select tbl_city_id,tbl_city_name from tbl_city where 1 and tbl_city_flag=0");
										 while($row = mysqli_fetch_array($sql)){
										 ?>
										 <option value="<?=$row['tbl_city_id'];?>"><?=$row['tbl_city_name'];?></option>
										 <?php 
										 }
										 ?>
									</select>

								</div>
								<div class="col-md-6">
									<button type="button" class="btn btn-primary" data-bs-dismiss="offcanvas" >Cancel</button>
								</div>
								<div class="col-md-6">
									<button class="btn btn-primary" type="submit" name="new_lead_form">Create</button>
								</div>
							</form>
						</div>
					</div>
					
					<!-- right offcanvas re-assign leads -->
					<div class="offcanvas offcanvas-end" tabindex="-1" id="rightOffcanvas1" aria-labelledby="rightOffcanvasLabel">
						<div class="offcanvas-header">
							<h4 class="offcanvas-title mt-0" id="rightOffcanvasLabel">Reassign Leads</h4>
							<button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
						</div>
						<div class="offcanvas-body">
							<form class="row g-3" name="reassignleadForm" action="#" method="POST" onsubmit="return reassignvalidateForm()" enctype="multipart/form-data">
								<input type="hidden" id="selectedLeadIdsInput" name="selected_lead_ids" /> 
								<input type="hidden" id="newselectedLeadIdsInput" name="new_selected_lead_ids" />
								
								<div class="col-md-12">
								<label for="validationDefault02" class="form-label">Assigned User</label>
									<select class="form-control"  name="re-assigned_user" id="re-assigned_user" data-choices data-choices-sorting-false>
										<option value="">Select Assigned User</option>
										<?php
										echo "Select id,name from tbl_invite_user where 1 and flag=0";
										 $sql=mysqli_query($conn,"Select id,name from tbl_invite_user where 1 and flag=0");
										 while($row = mysqli_fetch_array($sql)){
										 ?>
										 <option value="<?=$row['id'];?>"><?=$row['name'];?></option>
										 <?php 
										 }
										 ?>
									</select>

								</div>
								
								<div class="col-md-6">
									<button type="button" class="btn btn-primary" data-bs-dismiss="offcanvas" >Cancel</button>
								</div>
								<div class="col-md-6">
									<button class="btn btn-primary" type="submit" name="reassign_lead_form">Re-assign</button>
								</div>
							</form>
						</div>
					</div>
					
					<!-- right offcanvas not connected -->
					<div class="offcanvas offcanvas-end" tabindex="-1" id="notConnectedRightOffcanvas" aria-labelledby="rightOffcanvasLabel">
						<div class="offcanvas-header">
							<h4 class="offcanvas-title mt-0" id="rightOffcanvasLabel">Followup(Not Connected)</h4>
							<button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
						</div>
						<div class="offcanvas-body">
							<form class="row g-3" name="notConnectedForm" action="" method="POST" onsubmit="return validateNotConnectedForm()" enctype="multipart/form-data">
								<input type="hidden" name="action" value="not_connected">
								<input type="hidden" name="lead_id" id="lead_id">
								<div class="col-md-12">
									<label for="lead_name" class="form-label">Lead Name</label>
									<input type="text" name="lead_name" id="lead_name" class="form-control" placeholder="e.g. Ravi Gupta" required readonly>
								</div>
								<div class="col-md-12">
									<label for="nc_followup_date" class="form-label">Select Followup Date & Time</label>
									<input type="date" class="date-input form-control" id="nc_followup_date" name="nc_followup_date">
									<input type="time" class="time-input form-control mt-2" id="nc_followup_time" name="nc_followup_time">
								</div>
								<div class="col-md-12">
									<label for="nc_intent" class="form-label">Intent</label>
									<select class="form-control" id="nc_intent" name="nc_intent">
										<option value="">Select Intent</option>
										<option value="Cold">Cold Lead</option>
										<option value="Warm">Warm Lead</option>
										<option value="Hot">Hot Lead</option>
									</select>
								</div>
								<div class="col-md-12">
									<label for="nc_reason" class="form-label">Reason</label>
									<select class="form-control" id="nc_reason" name="nc_reason">
										<option value="">Select Reason</option>
										<option value="Number Busy">Number Busy</option>
										<option value="Not Reachable">Not Reachable</option>
										<option value="Call Waiting">Call Waiting </option>
										<option value="Call Back ">Call Back </option>
										<option value="Out of service">Out of service</option>
										<option value="Out of network">Out of network</option>
										<option value="Ringing">Ringing</option>
										<option value="Switch Off">Switch off</option>
										<option value="Disconnected">Disconnected </option>
										<option value="Wrong number">Wrong number</option>
											<option value="Others">Others</option>
									</select>
								</div>
								<div class="col-md-12">
									<label for="nc_comments" class="form-label">Comments(Optional)</label>
									<textarea name="nc_comments" id="nc_comments" class="form-control" placeholder="e.g. Enter any followup comment..." rows="3"></textarea>
								</div>
								<div class="col-md-6">
									<button type="button" class="btn btn-primary" data-bs-dismiss="offcanvas">Cancel</button>
								</div>
								<div class="col-md-6">
									<button class="btn btn-primary" type="submit" name="not_connected_form">Create Followup</button>
								</div>
							</form>
						</div>
					</div>
					
					<!-- right offcanvas In Progress -->
					<div class="offcanvas offcanvas-end" tabindex="-1" id="InProgressRightOffcanvas" aria-labelledby="rightOffcanvasLabel">
						<div class="offcanvas-header">
							<h4 class="offcanvas-title mt-0" id="rightOffcanvasLabel">Followup(In Progress)</h4>
							<button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
						</div>
						<div class="offcanvas-body">
							<form class="row g-3" name="inProgressForm" action="" method="POST" onsubmit="return validateInProgressForm()" enctype="multipart/form-data">
								<input type="hidden" name="action" value="in_progress">
								<input type="hidden" name="inp_lead_id" id="inp_lead_id">
								<div class="col-md-12">
									<label for="validationDefault01" class="form-label">Lead Name</label>
									<input type="text" name="inp_lead_name" id="inp_lead_name" class="form-control"  placeholder="e.g. Ravi Gupta" readonly>
									
								</div>
								<div class="col-md-12">
									<label for="validationDefault02" class="form-label">Select Followup Date & Time</label>
									<input type="date" class="date-input form-control" id="inp_followup_date" name="inp_followup_date" >
									<input type="time" class="time-input form-control" id="inp_followup_time" name="inp_followup_time">
								</div>
								<div class="col-md-12">
								<label for="validationDefault02" class="form-label">Intent</label>
									<select class="form-control" id="choices-single-no-sorting" name="inp_intent" id="inp_intent" data-choices data-choices-sorting-false>
									<option value="">Select Intent</option>
									<option value="Cold">Cold Lead</option>
									<option value="Warm">Warm Lead</option>
									<option value="Hot">Hot Lead</option>
									</select>
								</div>
								<!--div class="col-md-12">
								<label for="validationDefault02" class="form-label">Reason</label>
									<select class="form-control" id="choices-single-no-sorting" name="inp_reason" id="inp_reason" data-choices data-choices-sorting-false>
									<option value="">Select Reason</option>
									<option value="Not Responding">Not Responding</option>
									<option value="Ringing">Ringing</option>
									<option value="Busy">Busy</option>
									<option value="Not Reachable">Not Reachable</option>
									<option value="Switch off">Switch off</option>
									<option value="Call Back">Call Back</option>
									<option value="Call Disconnected">Call Disconnected</option>
									<option value="Incoming not available">Incoming not available</option>
									<option value="Dailed number does not exist">Dailed number does not exist</option>
									<option value="Unable to connect">Unable to connect</option>
									</select>

								</div-->
								<div class="col-md-12">
									<label for="validationDefault01" class="form-label">Comments(Optional)</label>
									 <textarea name="inp_comments" id="inp_comments" class="form-control" placeholder="e.g. Enter any followup comment..." rows="3"></textarea>
									
								</div>
								<div class="col-md-6">
									<button type="button" class="btn btn-primary" data-bs-dismiss="offcanvas" >Cancel</button>
								</div>
								<div class="col-md-6">
									<button class="btn btn-primary" type="submit" name="in_progress_form">Create Followup</button>
								</div>
							</form>
						</div>
					</div>
					
					<!-- right offcanvas SV Scheduled -->
					<div class="offcanvas offcanvas-end" tabindex="-1" id="svScheduledRightOffcanvas" aria-labelledby="rightOffcanvasLabel">
						<div class="offcanvas-header">
							<h4 class="offcanvas-title mt-0" id="rightOffcanvasLabel">SV Schedule &  Followup</h4>
							<button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
						</div>
						<div class="offcanvas-body">
							<form class="row g-3" name="svScheduledForm" action="#" method="POST" onsubmit="return validateSVScheduledForm()" enctype="multipart/form-data">
								<input type="hidden" name="action" value="sv_scheduled">
								<input type="hidden" name="svs_lead_id" id="svs_lead_id">
								<div class="col-md-12">
									<label for="validationDefault01" class="form-label">Lead Name</label>
									<input type="text" name="svs_lead_name" id="svs_lead_name" class="form-control"  placeholder="e.g. Ravi Gupta" readonly>
									
								</div>
								<div class="col-md-12">
									<label for="validationDefault02" class="form-label">Select Sitevisit Date & Time</label>
									<input type="date" class="date-input form-control" id="svs_followup_date_sv" name="svs_followup_date_sv">
									<input type="time" class="time-input form-control" id="svs_followup_time_sv" name="svs_followup_time_sv">
								</div>
								<div class="col-md-12">
								<label for="validationDefault02" class="form-label">Type of Site Visit</label>
								<div class="form-check form-check-inline">
									 <input class="form-check-input" type="radio" name="svs_OnVideo" id="svs_OnVideo" value="OnVideo">
									 <label class="form-check-label" for="inlineRadio1">On Video</label>
								</div>
								<div class="form-check form-check-inline">
									 <input class="form-check-input" type="radio" name="svs_OnVideo" id="svs_OnVideo" value="OnSite">
									 <label class="form-check-label" for="inlineRadio2">On Site</label>
								</div>
								</div>
								<!--div class="col-md-12">
								<label for="validationDefault02" class="form-label">Projects</label>
								
									<select class="form-control" id="choices-multiple-remove-button" data-choices data-choices-removeItem name="svs_project_name[]" multiple>
										 <option value="" >Select Project</option>
										 <?php
										 $sql=mysqli_query($conn,"Select tbl_project_id,tbl_project_name from tbl_project where 1 and tbl_project_flag=0");
										 while($row = mysqli_fetch_array($sql)){
										 ?>
										 <option value="<?=$row['tbl_project_id'];?>"><?=$row['tbl_project_name'];?></option>
										 <?php 
										 }
										 ?>
									</select>


								</div-->
								<div class="col-md-12">
                                    <label for="svs_project_display" class="form-label">Projects</label>
                                    <input type="text" id="svs_project_display" class="form-control" placeholder="Selected Projects" readonly>
                                </div>
                                
                                <div id="hiddenProjectInputs"></div>
                                
								<div class="col-md-12">
								<label for="validationDefault02" class="form-label">Intent</label>
									<select class="form-control" id="choices-single-no-sorting" name="svs_intent" id="svs_intent" data-choices data-choices-sorting-false>
									<option value="">Select Intent</option>
									<option value="Cold">Cold Lead</option>
									<option value="Warm">Warm Lead</option>
									<option value="Hot">Hot Lead</option>
									</select>
								</div>
								
								<div class="col-md-12">
									<label for="validationDefault01" class="form-label">Site Visit Comments(Optional)</label>
									 <textarea name="svs_comments" id="svs_comments" class="form-control" placeholder="e.g. Enter any site visit comments..." rows="3"></textarea>
									
								</div>
								<div class="col-md-12">
									<label for="validationDefault02" class="form-label">Select Followup Date & Time</label>
									<input type="date" class="date-input form-control" id="svs_followup_date" name="svs_followup_date">
									<input type="time" class="time-input form-control" id="svs_followup_time" name="svs_followup_time">
								</div>
								<div class="col-md-6">
									<button type="button" class="btn btn-primary" data-bs-dismiss="offcanvas" >Cancel</button>
								</div>
								<div class="col-md-6">
									<button class="btn btn-primary" type="submit" name="sv_scheduled_form">Save Site Visit</button>
								</div>
							</form>
						</div>
					</div>
					
					<!-- right offcanvas SV Completed -->
					<div class="offcanvas offcanvas-end" tabindex="-1" id="svCompletedRightOffcanvas" aria-labelledby="rightOffcanvasLabel">
						<div class="offcanvas-header">
							<h4 class="offcanvas-title mt-0" id="rightOffcanvasLabel">Site Visit Done &  Followup</h4>
							<button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
						</div>
						<div class="offcanvas-body">
							<form class="row g-3" name="svCompletedForm" action="#" method="POST" onsubmit="return validateSVCompletedForm()" enctype="multipart/form-data">
								<input type="hidden" name="action" value="sv_completed">
								<input type="hidden" name="svc_lead_id" id="svc_lead_id">
								<div class="col-md-12">
									<label for="validationDefault01" class="form-label">Lead Name</label>
									<input type="text" name="svc_lead_name" id="svc_lead_name" class="form-control"  placeholder="e.g. Ravi Gupta" readonly>
									
								</div>
								<div class="col-md-12">
									<label for="validationDefault02" class="form-label">Select Sitevisit Date & Time</label>
									<input type="date" class="date-input form-control" id="svc_followup_date_sv" name="svc_followup_date_sv">
									<input type="time" class="time-input form-control" id="svc_followup_time_sv" name="svc_followup_time_sv">
								</div>
								<!--div class="col-md-12">
								<label for="validationDefault02" class="form-label">Projects</label>
									<select class="form-control" id="choices-multiple-remove-button" data-choices data-choices-removeItem name="svc_project_name">
										 <option value="" >Select Project</option>
										 <?php
										 $sql=mysqli_query($conn,"Select tbl_project_id,tbl_project_name from tbl_project where 1 and tbl_project_flag=0");
										 while($row = mysqli_fetch_array($sql)){
										 ?>
										 <option value="<?=$row['tbl_project_id'];?>"><?=$row['tbl_project_name'];?></option>
										 <?php 
										 }
										 ?>
									</select>


								</div-->
								<div class="col-md-12">
                                    <label for="svc_project_display" class="form-label">Projects</label>
                                    <input type="text" id="svc_project_display" class="form-control" placeholder="Selected Projects" readonly>
                                </div>
                                
                                <div id="hiddensvcProjectInputs"></div>
								<div class="col-md-12">
								<label for="validationDefault02" class="form-label">Intent</label>
									<select class="form-control" id="choices-single-no-sorting" name="svc_intent" id="svc_intent" data-choices data-choices-sorting-false>
									<option value="">Select Intent</option>
									<option value="Cold">Cold Lead</option>
									<option value="Warm">Warm Lead</option>
									<option value="Hot">Hot Lead</option>
									</select>
								</div>
								<div class="col-md-12">
								<label for="validationDefault02" class="form-label">Type of Site Visit</label>
								<div class="form-check form-check-inline">
									 <input class="form-check-input" type="radio" name="svc_OnVideo" id="svc_OnVideo" value="OnVideo">
									 <label class="form-check-label" for="inlineRadio1">On Video</label>
								</div>
								<div class="form-check form-check-inline">
									 <input class="form-check-input" type="radio" name="svc_OnSite" id="svc_OnSite" value="OnSite">
									 <label class="form-check-label" for="inlineRadio2">On Site</label>
								</div>
								</div>
								<div class="col-md-12">
									<label for="validationDefault01" class="form-label">Duration</label>
									<input type="text" name="svc_duration" id="svc_duration" class="form-control"  placeholder="e.g. 30 mins">
									
								</div>
								<div class="col-md-12">
									<label for="validationDefault01" class="form-label">Site Visit Comments(Optional)</label>
									 <textarea name="svc_comments" id="svc_comments" class="form-control" placeholder="e.g. Enter any site visit comments..." rows="3"></textarea>
									
								</div>
								<div class="col-md-12">
									<label for="validationDefault02" class="form-label">Next Followup Date & Time</label>
									<input type="date" class="date-input form-control" id="svc_followup_date" name="svc_followup_date">
									<input type="time" class="time-input form-control" id="svc_followup_time" name="svc_followup_time">
								</div>
								<div class="col-md-6">
									<button type="button" class="btn btn-primary" data-bs-dismiss="offcanvas" >Cancel</button>
								</div>
								<div class="col-md-6">
									<button class="btn btn-primary" type="submit" name="sv_completed_form">Confirm</button>
								</div>
							</form>
						</div>
					</div>
					
					<!-- right offcanvas EOI Completed -->
					<div class="offcanvas offcanvas-end" tabindex="-1" id="eoiCompletedRightOffcanvas" aria-labelledby="rightOffcanvasLabel">
						<div class="offcanvas-header">
							<h4 class="offcanvas-title mt-0" id="rightOffcanvasLabel">Token Done &  Followup</h4>
							<button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
						</div>
						<div class="offcanvas-body">
							<form class="row g-3" name="eoiCompletedForm" action="#" method="POST" onsubmit="return validateEoiCompletedForm()" enctype="multipart/form-data">
								<input type="hidden" name="action" value="eoi_completed">
								<input type="hidden" name="eoi_lead_id" id="eoi_lead_id">
								<div class="col-md-12">
									<label for="validationDefault01" class="form-label">Lead Name</label>
									<input type="text" name="eoi_lead_name" id="eoi_lead_name" class="form-control"  placeholder="e.g. Ravi Gupta" readonly>
									
								</div>
								<div class="col-md-12">
									<label for="validationDefault02" class="form-label">Token Date & Time</label>
									<input type="date" class="date-input form-control" id="eoi_token_date" name="eoi_token_date" required>
									<input type="time" class="time-input form-control" id="eoi_token_time" name="eoi_token_time" required>
								</div>
								<!--div class="col-md-12">
								<label for="validationDefault02" class="form-label">Projects</label>
									<select class="form-control" id="choices-multiple-remove-button" data-choices data-choices-removeItem name="eoi_project_name">
										 <option value="" >Select Project</option>
										 <?php
										 $sql=mysqli_query($conn,"Select tbl_project_id,tbl_project_name from tbl_project where 1 and tbl_project_flag=0");
										 while($row = mysqli_fetch_array($sql)){
										 ?>
										 <option value="<?=$row['tbl_project_id'];?>"><?=$row['tbl_project_name'];?></option>
										 <?php 
										 }
										 ?>
									</select>


								</div-->
								<div class="col-md-12">
                                    <label for="eoi_project_display" class="form-label">Projects</label>
                                    <input type="text" id="eoi_project_display" class="form-control" placeholder="Selected Projects" readonly>
                                </div>
                                
                                <div id="hiddeneoiProjectInputs"></div>
                                
								<div class="col-md-12">
									<label for="validationDefault01" class="form-label">Token Amount</label>
									<input type="text" name="eoi_token_amount" id="eoi_token_amount" class="form-control"  placeholder="e.g. 10,00,000">
									
								</div>
								<div class="col-md-12">
									<label for="validationDefault02" class="form-label">Validity Date</label>
									<input type="date" class="date-input form-control" id="eoi_validity_date" name="eoi_validity_date">
								</div>
								<div class="col-md-12">
									<label for="validationDefault01" class="form-label">Total Unit Price</label>
									<input type="text" name="eoi_unit_price" id="eoi_unit_price" class="form-control"  placeholder="e.g. 10,00,000">
									
								</div>
								<div class="col-md-12">
									<label for="validationDefault01" class="form-label">Unit No.</label>
									<input type="text" name="eoi_unit_no" id="eoi_unit_no" class="form-control"  placeholder="e.g. B101">
									
								</div>
								
								<div class="col-md-12">
									<label for="validationDefault01" class="form-label">Any Comments(Optional)</label>
									 <textarea name="eoi_comments" id="eoi_comments" class="form-control" placeholder="e.g. Enter any site visit comments..." rows="3"></textarea>
									
								</div>
								<div class="col-md-12">
									<label for="validationDefault02" class="form-label">Select Followup Date & Time</label>
									<input type="date" class="date-input form-control" id="eoi_followup_date" name="eoi_followup_date">
									<input type="time" class="time-input form-control" id="eoi_followup_time" name="eoi_followup_time">
								</div>
								<div class="col-md-6">
									<button type="button" class="btn btn-primary" data-bs-dismiss="offcanvas" >Cancel</button>
								</div>
								<div class="col-md-6">
									<button class="btn btn-primary" type="submit" name="eoi_completed_form">Confirm</button>
								</div>
							</form>
						</div>
					</div>
					
					<!-- right offcanvas booking Completed -->
					<div class="offcanvas offcanvas-end" tabindex="-1" id="bookingCompletedRightOffcanvas" aria-labelledby="rightOffcanvasLabel">
						<div class="offcanvas-header">
							<h4 class="offcanvas-title mt-0" id="rightOffcanvasLabel">Booking Done</h4>
							<button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
						</div>
						<div class="offcanvas-body">
							
							<form class="row g-3" name="bookingCompletedForm" action="#" method="POST" onsubmit="return validateBookingCompletedForm()" enctype="multipart/form-data">
								<input type="hidden" name="action" value="booking_completed">
							    <input type="hidden" name="booking_lead_id" id="booking_lead_id">
								<div class="col-md-12">
									<label for="validationDefault01" class="form-label">Lead Name</label>
									<input type="text" name="booking_lead_name" id="booking_lead_name" class="form-control"  placeholder="e.g. Ravi Gupta" readonly>
									
								</div>
								<div class="col-md-12">
									<label for="validationDefault02" class="form-label">Booking Date & Time</label>
									<input type="date" class="date-input form-control" id="booking_followup_date" name="booking_followup_date">
									<input type="time" class="time-inputform-control" id="booking_followup_time" name="booking_followup_time">
								</div>
								
								<div class="col-md-12">
									<label for="validationDefault01" class="form-label">Net Purchase Price</label>
									<input type="text" name="booking_purchase_price" id="booking_purchase_price" class="form-control"  placeholder="e.g. 10,00,000">
									
								</div>
								<div class="col-md-12">
									<label for="validationDefault01" class="form-label">Amount Paid</label>
									<input type="text" name="booking_amount_paid" id="booking_amount_paid" class="form-control"  placeholder="e.g. 10,00,000">
									
								</div>
								<div class="col-md-12">
									<label for="validationDefault01" class="form-label">Unit No.</label>
									<input type="text" name="booking_unit_no" id="booking_unit_no" class="form-control"  placeholder="e.g. B101">
									
								</div>
								
								<div class="col-md-12">
									<label for="validationDefault01" class="form-label">Any Comments(Optional)</label>
									 <textarea name="booking_comments" id="booking_comments" class="form-control" placeholder="e.g. Enter any site visit comments..." rows="3"></textarea>
									
								</div>
								<div class="col-md-6">
									<button type="button" class="btn btn-primary" data-bs-dismiss="offcanvas" >Cancel</button>
								</div>
								<div class="col-md-6">
									<button class="btn btn-primary" type="submit" name="booking_completed_form">Confirm</button>
								</div>
							</form>
						</div>
					</div>
					
					<!-- right offcanvas Dead -->
					<div class="offcanvas offcanvas-end" tabindex="-1" id="deadRightOffcanvas" aria-labelledby="rightOffcanvasLabel">
						<div class="offcanvas-header">
							<h4 class="offcanvas-title mt-0" id="rightOffcanvasLabel">Mark Lead as Dead</h4>
							<button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
						</div>
						<div class="offcanvas-body">
							
							<form class="row g-3" name="deadForm" action="#" method="POST" onsubmit="return validateDeadForm()" enctype="multipart/form-data">
								<input type="hidden" name="action" value="dead">
							    <input type="hidden" name="dead_lead_id" id="dead_lead_id">
								<div class="col-md-12">
									<label for="validationDefault01" class="form-label">Lead Name</label>
									<input type="text" name="dead_lead_name" id="dead_lead_name" class="form-control"  placeholder="e.g. Ravi Gupta" readonly>
									
								</div>
								<div class="col-md-12">
								<label for="validationDefault02" class="form-label">Reason</label>
									<select class="form-control" id="choices-single-no-sorting" name="dead_reason" id="dead_reason" data-choices data-choices-sorting-false>
									<option value="">Select Reason</option>
									<option value="Not interested">Not interested</option>
									<option value="Not Enquired">Not Enquired</option>
									<option value="Fake /Spam Lead">Fake /Spam Lead</option>
									<option value="Budget Issue">Budget Issue</option>
									<option value="Location Mismatch">Location Mismatch</option>
									<option value="Possession mismatch">Possession mismatch</option>
									<!--<option value="Call Disconnected">Call Disconnected</option>-->
									<!--<option value="Incoming not available">Incoming not available</option>-->
									<!--<option value="Dailed number does not exist">Dailed number does not exist</option>-->
									<!--<option value="Unable to connect">Unable to connect</option>-->
									</select>

								</div>
								<div class="col-md-12">
									<label for="validationDefault01" class="form-label">Any Comments(Optional)</label>
									 <textarea name="dead_comments" id="dead_comments" class="form-control" placeholder="e.g. Enter any comments..."  rows="3"></textarea>
									
								</div>
								<div class="col-md-6">
									<button type="button" class="btn btn-primary" data-bs-dismiss="offcanvas" >Cancel</button>
								</div>
								<div class="col-md-6">
									<button class="btn btn-primary" type="submit" name="dead_form">Mark as Dead</button>
								</div>
							</form>
						</div>
					</div>
					<?php
					
					// Get project IDs from session if they exist
                    $projectFilter = "";
                    if (isset($_SESSION['selected_projects']) && !empty($_SESSION['selected_projects'])) {
                        // Check if the selected_projects is a JSON string and decode it
                        $projectIds = is_string($_SESSION['selected_projects']) 
                            ? json_decode($_SESSION['selected_projects'], true) 
                            : $_SESSION['selected_projects'];
                        
                        // Make sure we have an array
                        if (is_array($projectIds) && !empty($projectIds)) {
                            $projectIdsStr = implode(',', array_map('intval', $projectIds));
                            $projectFilter = "AND tbl_lead_user_id IN (
                                SELECT tbl_lead_user_id 
                                FROM tbl_lead_user_projects 
                                WHERE tbl_lead_user_prj_id IN ($projectIdsStr)
                            )";
                        }
                    }
					
					$cond="";
					if($_SESSION['role'] =='STANDARD'){
					    $cond = "AND tbl_lead_user_assigned_user_id = " . $_SESSION['user_id'] . " ";
					}
					$all_cnt=mysqli_num_rows(mysqli_query($conn,"select * from tbl_lead_user where 1 and tbl_lead_user_flag=0 $projectFilter  $cond"));
					$all_new=mysqli_num_rows(mysqli_query($conn,"select * from tbl_lead_user where 1 and tbl_lead_user_flag=0 and tbl_lead_user_status='new' $projectFilter  $cond"));
					$all_followup=mysqli_num_rows(mysqli_query($conn,"select * from tbl_lead_user where 1 and tbl_lead_user_flag=0 and tbl_lead_user_status in('Not Connected','In Progress') $projectFilter  $cond"));
					$all_sv_sch=mysqli_num_rows(mysqli_query($conn,"select * from tbl_lead_user where 1 and tbl_lead_user_flag=0 and tbl_lead_user_status in('SV Scheduled') $projectFilter  $cond"));
					$all_sv_sc=mysqli_num_rows(mysqli_query($conn,"select * from tbl_lead_user where 1 and tbl_lead_user_flag=0 and tbl_lead_user_status in('SV Completed') $projectFilter  $cond"));
					$all_booking_eoi=mysqli_num_rows(mysqli_query($conn,"select * from tbl_lead_user where 1 and tbl_lead_user_flag=0 and tbl_lead_user_status in('EOI Completed','Booking Completed') $projectFilter  $cond"));
					$all_dead=mysqli_num_rows(mysqli_query($conn,"select * from tbl_lead_user where 1 and tbl_lead_user_flag=0 and tbl_lead_user_status in('Dead Lead') $projectFilter $cond"));
					?>
					<div class="row">
                         <div class="col-lg-12">
                              <div class="card">
                                   <div class="card-header border-0">
                                        <div class="row justify-content-between">
                                            <ul class="nav nav-tabs" id="counter-ajax">
                                              <li class="nav-item">
                                                <a href="#home" data-bs-toggle="tab" aria-expanded="false" class="nav-link active">
                                                  <span class="d-block d-sm-none"><i class="bx bx-home"></i> All(<?php echo $all_cnt; ?>)</span>
                                                  <span class="d-none d-sm-block">All(<?php echo $all_cnt; ?>)</span>
                                                </a>
                                              </li>
                                              <li class="nav-item">
                                                <a href="#profile" data-bs-toggle="tab" aria-expanded="true" class="nav-link ">
                                                  <span class="d-block d-sm-none"><i class="bx bx-user"></i> New(<?php echo $all_new; ?>)</span>
                                                  <span class="d-none d-sm-block">New(<?php echo $all_new; ?>)</span>
                                                </a>
                                              </li>
                                              <li class="nav-item">
                                                <a href="#messages" data-bs-toggle="tab" aria-expanded="false" class="nav-link">
                                                  <span class="d-block d-sm-none"><i class="ri-mail-line"></i> FLWUP(<?php echo $all_followup; ?>)</span>
                                                  <span class="d-none d-sm-block">Followup(<?php echo $all_followup; ?>)</span>
                                                </a>
                                              </li>
                                              <li class="nav-item">
                                                <a href="#svscheduled" data-bs-toggle="tab" aria-expanded="false" class="nav-link">
                                                  <span class="d-block d-sm-none"><i class="ri-mail-line"></i> SVS(<?php echo $all_sv_sch; ?>)</span>
                                                  <span class="d-none d-sm-block">SV Scheduled(<?php echo $all_sv_sch; ?>)</span>
                                                </a>
                                              </li>
                                              <li class="nav-item">
                                                <a href="#svcompleted" data-bs-toggle="tab" aria-expanded="false" class="nav-link">
                                                  <span class="d-block d-sm-none"><i class="ri-mail-line"></i> SVC(<?php echo $all_sv_sc; ?>)</span>
                                                  <span class="d-none d-sm-block">SV Completed(<?php echo $all_sv_sc; ?>)</span>
                                                </a>
                                              </li>
                                              <li class="nav-item">
                                                <a href="#bookingeois" data-bs-toggle="tab" aria-expanded="false" class="nav-link">
                                                  <span class="d-block d-sm-none"><i class="ri-mail-line"></i> BKG/EOI(<?php echo $all_booking_eoi; ?>)</span>
                                                  <span class="d-none d-sm-block">Booking/EOIs(<?php echo $all_booking_eoi; ?>)</span>
                                                </a>
                                              </li>
                                              <li class="nav-item">
                                                <a href="#dead" data-bs-toggle="tab" aria-expanded="false" class="nav-link">
                                                  <span class="d-block d-sm-none"><i class="ri-mail-line"></i> Dead(<?php echo $all_dead; ?>)</span>
                                                  <span class="d-none d-sm-block">Dead(<?php echo $all_dead; ?>)</span>
                                                </a>
                                              </li>
                                            </ul>

						<div class="tab-content text-muted">
							
								<div class="tab-pane show active card-body" id="home">
                                    <div class="py-3">
                                        <div id="table-gridjs"></div>
                                    </div>
                            </div>
							<div class="tab-pane " id="profile">
								<div class="py-3">
                                    <div id="table-gridjs-new"></div>
                                </div>
							</div>
							<div class="tab-pane" id="messages">
								<div class="py-3">
                                    <div id="table-gridjs-messages"></div>
                                </div>
							</div>
							<div class="tab-pane" id="svscheduled">
								<div class="py-3">
                                    <div id="table-gridjs-new-svscheduled"></div>
                                </div>
							</div>
							<div class="tab-pane" id="svcompleted">
								<div class="py-3">
                                    <div id="table-gridjs-new-svcompleted"></div>
                                </div>
							</div>
							<div class="tab-pane" id="bookingeois">
								<div class="py-3">
                                    <div id="table-gridjs-new-bookingeois"></div>
                                </div>
							</div>
							<div class="tab-pane" id="dead">
								<div class="py-3">
                                    <div id="table-gridjs-new-dead"></div>
                                </div>
							</div>
						</div> 
                                            
                                        </div>
                                   </div>
                              </div>
                         </div>
                    </div>
					
					
						
					

                <div class="row">
                    <div class="col-xl-12">
                        <div class="card">
						
                            <div class="card-body">
                                <div>
                                    <div class="py-3">
                                        <div id="table-gridjs"></div>
                                    </div>
                               
                                    
                                </div>
                            </div>
                        </div>


                    </div> <!-- end card body -->

                   


                </div> <!-- end row -->

            </div>
            <!-- End Container Fluid -->


<script>
        document.getElementById("lead_mobile").addEventListener("input", function () {
            this.value = this.value.replace(/[^\d+]/g, '');
        });
        document.getElementById("alt_lead_mobile").addEventListener("input", function () {
            this.value = this.value.replace(/[^\d+]/g, '');
        });
        // JavaScript Validation Function
		//document.getElementById('basic-datepicker').flatpickr();
        function validateForm() {
            var leadname = document.forms["leadForm"]["lead_name"].value;
			var mobile = document.forms["leadForm"]["lead_mobile"].value;
			var source = document.forms["leadForm"]["lead_source"].value;
			var pname = document.forms["leadForm"]["project_name[]"].value;
			var assigneduser = document.forms["leadForm"]["assigned_user"].value;
            var errorMessage = "";

            // Check if the name is empty
            if (leadname == "") {
                errorMessage += "Lead Name is required.\n";
            }
			if (mobile == "") {
                errorMessage += "Mobile is required.\n";
            }
			// Check if the name is empty
            if (source == "") {
                errorMessage += "Lead Source. is required.\n";
            }
			if (pname == "") {
                errorMessage += "Project. is required.\n";
            }
            if (assigneduser == "") {
                errorMessage += "Assigned user. is required.\n";
            }
			
            // If there is any error, display it and prevent form submission
            if (errorMessage != "") {
                alert(errorMessage);
                return false; // prevent form submission
            }
            return true; // form is valid
        }
        
        function reassignvalidateForm() {
            
			var assigneduser = document.forms["reassignleadForm"]["re-assigned_user"].value;
            var errorMessage = "";

            // Check if the name is empty
            if (assigneduser == "") {
                errorMessage += "Assigned user. is required.\n";
            }
			
            // If there is any error, display it and prevent form submission
            if (errorMessage != "") {
                alert(errorMessage);
                return false; // prevent form submission
            }
            return true; // form is valid
        }
        
    </script>
		

	
<?php
include('footer.php');
?>

 <?php
 
 if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['reassign_lead_form'])) {
    if (!empty($_POST['re-assigned_user'])) {
        $assignedUserId = intval($_POST['re-assigned_user']);
        
        // Get all selected lead IDs
        $selectedLeadIds = [];
        if (!empty($_POST['selected_lead_ids'])) {
            $selectedLeadIds = explode(',', $_POST['selected_lead_ids']);
        }

        $newSelectedLeadIds = [];
        if (!empty($_POST['new_selected_lead_ids'])) {
            $newSelectedLeadIds = explode(',', $_POST['new_selected_lead_ids']);
        }

        // Merge both arrays if needed
        $allLeadIds = array_merge($selectedLeadIds, $newSelectedLeadIds);
        $allLeadIds = array_unique($allLeadIds); // remove duplicates

        foreach ($allLeadIds as $leadId) {
            $leadId = intval($leadId);

            // Fetch the project id for this lead (assuming you have it)
           
            $projectQuery = mysqli_query($conn, "SELECT tbl_lead_user_prj_id FROM tbl_lead_user_projects WHERE 1 and tbl_lead_user_id = '$leadId'");
            $leadRow = mysqli_fetch_assoc($projectQuery);

            if ($leadRow) {
                $projectId = $leadRow['tbl_lead_user_prj_id'];

                // Now check if the user has access to this project
                $checkAccessQuery = mysqli_query($conn, "SELECT tbl_lead_user_access_projects_user_id FROM tbl_lead_user_access_projects WHERE tbl_lead_user_access_projects_user_id = '$assignedUserId' AND tbl_lead_user_access_projects_project_id = '$projectId'");

                if (mysqli_num_rows($checkAccessQuery) > 0) {
                    // User has access, so update lead assignment
                    //$updateLeadQuery = mysqli_query($conn, "UPDATE tbl_lead_user SET tbl_lead_user_assigned_user_id = '$assignedUserId', tbl_lead_user_assigned_date = '".date('Y-m-d h:i:s:A')."' WHERE tbl_lead_user_id = '$leadId'");
                    // Get current assigned user before reassigning
                        $currentAssignedQuery = mysqli_query($conn, "SELECT tbl_lead_user_assigned_user_id FROM tbl_lead_user WHERE tbl_lead_user_id = '$leadId'");
                        $currentAssignedData = mysqli_fetch_assoc($currentAssignedQuery);
                        $previousAssignedUserId = $currentAssignedData ? intval($currentAssignedData['tbl_lead_user_assigned_user_id']) : null;
                        
                        // Log reassignment
                        $reassignedByUserId = $_SESSION['user_id']; // Replace with your logged-in user session
                        $reassignedDate = date('Y-m-d H:i:s');
                        
                        $insertHistoryQuery = mysqli_query($conn, "
                            INSERT INTO lead_reassignment_history 
                                (lead_id, reassigned_from_user_id, reassigned_to_user_id, reassigned_by_user_id, reassigned_date) 
                            VALUES 
                                ('$leadId', " . ($previousAssignedUserId !== null ? "'$previousAssignedUserId'" : "NULL") . ", '$assignedUserId', '$reassignedByUserId', '$reassignedDate')
                        ");
                        
                        // Now update the lead assignment
                        $updateLeadQuery = mysqli_query($conn, "
                            UPDATE tbl_lead_user 
                            SET tbl_lead_user_assigned_user_id = '$assignedUserId', 
                                tbl_lead_user_assigned_date = '$reassignedDate' 
                            WHERE tbl_lead_user_id = '$leadId'
                        ");
                    
                } else {
                    // Now give the user has access to this project
                     $insertQuery = mysqli_query($conn, "INSERT INTO tbl_lead_user_access_projects (tbl_lead_user_access_projects_user_id, tbl_lead_user_access_projects_project_id) VALUES ('$assignedUserId', '$projectId')");
                    // User does not have access, you can log or handle it
                    // Now update the lead user table
                    // $updateLeadQuery = mysqli_query($conn, "
                    //     UPDATE tbl_lead_user 
                    //     SET tbl_lead_user_assigned_user_id = '$assignedUserId', 
                    //         tbl_lead_user_assigned_date = '" . date('Y-m-d H:i:s') . "' 
                    //     WHERE tbl_lead_user_id = '$leadId'
                    // ");
                    // Get current assigned user before reassigning
                    $currentAssignedQuery = mysqli_query($conn, "SELECT tbl_lead_user_assigned_user_id FROM tbl_lead_user WHERE tbl_lead_user_id = '$leadId'");
                    $currentAssignedData = mysqli_fetch_assoc($currentAssignedQuery);
                    $previousAssignedUserId = $currentAssignedData ? intval($currentAssignedData['tbl_lead_user_assigned_user_id']) : null;
                    
                    // Log reassignment
                    $reassignedByUserId = $_SESSION['user_id']; // Replace with your logged-in user session
                    $reassignedDate = date('Y-m-d H:i:s');
                    
                    $insertHistoryQuery = mysqli_query($conn, "
                        INSERT INTO lead_reassignment_history 
                            (lead_id, reassigned_from_user_id, reassigned_to_user_id, reassigned_by_user_id, reassigned_date) 
                        VALUES 
                            ('$leadId', " . ($previousAssignedUserId !== null ? "'$previousAssignedUserId'" : "NULL") . ", '$assignedUserId', '$reassignedByUserId', '$reassignedDate')
                    ");
                    
                    // Now update the lead assignment
                    $updateLeadQuery = mysqli_query($conn, "
                        UPDATE tbl_lead_user 
                        SET tbl_lead_user_assigned_user_id = '$assignedUserId', 
                            tbl_lead_user_assigned_date = '$reassignedDate' 
                        WHERE tbl_lead_user_id = '$leadId'
                    ");
                    //echo "<script>alert('Give the access to User for project for Lead ID: $leadId. Reassign this lead.');</script>";
                }
            }
        }
        
        unset($_SESSION['selectedStatus']);
        unset($_SESSION['selectedStatusnew']);
        echo "<script language='javascript'>
            Swal.fire({
                title: 'Success!',
                text: 'Leads reassigned successfully.',
                icon: 'success',
                confirmButtonClass: 'btn btn-primary w-xs mt-2',
                buttonsStyling: false,
                showCloseButton: false
            }).then(function() {
                window.location.href = 'dashboard-manager.php';
            });
          </script>";
        exit;
    } else {
        echo "<script>alert('Please select a user to reassign the leads.');</script>";
    }
}

 
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST"  && isset($_POST['new_lead_form'])) {
    // Retrieve form data
	if($_POST['lead_mobile'] !=''){
	    $msg_project_id='';
		$check_profile=mysqli_num_rows(mysqli_query($conn,"Select tbl_lead_user_profile_id from tbl_lead_user_profile where 1 and tbl_lead_user_profile_flag=0 and tbl_lead_user_profile_mobile='".$_POST['lead_mobile']."'"));
		if($check_profile <= 0){
			$sql="insert into tbl_lead_user_profile set tbl_lead_user_profile_name='".$_POST['lead_name']."',tbl_lead_user_profile_email='".$_POST['lead_email']."',tbl_lead_user_profile_mobile='".$_POST['lead_mobile']."',tbl_lead_user_profile_alt_mobile='".$_POST['alt_lead_mobile']."',tbl_lead_user_profile_cdate='".date('Y-m-d H:i:s')."',tbl_lead_user_profile_flag=0,tbl_lead_user_profile_cuser='ADMIN'";
			$result=mysqli_query($conn,$sql);
			$user_profile_id=$conn->insert_id;
			if($result){
			    if($_POST['city']==''){
    			    $_POST['city']=0;
    			}
				$source_name=get_source_name($_POST['lead_source']);
		    	$sql="insert into tbl_lead_user set tbl_lead_user_profile_id='".$user_profile_id."',tbl_lead_user_mobile='".$_POST['lead_mobile']."',tbl_lead_user_alt_mobile='".$_POST['alt_lead_mobile']."',tbl_lead_user_assigned_date='".date('Y-m-d H:i:s')."',tbl_lead_user_source_id='".$_POST['lead_source']."',tbl_lead_user_source_name='".$source_name."',tbl_lead_user_assigned_user_id='".$_POST['assigned_user']."',tbl_lead_user_regdate='".date('Y-m-d')."',tbl_lead_user_cdate='".date('Y-m-d H:i:s')."',tbl_lead_user_flag=0,tbl_lead_user_city_id='".$_POST['city']."',tbl_lead_user_cuser='ADMIN'";
				$lead_result=mysqli_query($conn,$sql);
				$lead_id=$conn->insert_id;
				if($lead_result){
				    
				    if (isset($_POST['project_name']) && is_array($_POST['project_name'])) {
                        $project_ids = $_POST['project_name'];
                        $project_ids ;
                        // Insert selected projects into database
                        foreach ($project_ids as $project_id) {
                            $sql = "INSERT INTO tbl_lead_user_projects (tbl_lead_user_id, tbl_lead_user_prj_id) VALUES ('$lead_id', '$project_id')";
                            mysqli_query($conn, $sql);
                            $msg_project_id = $project_id;
                            $sql_update="UPDATE tbl_lead_user SET tbl_lead_user_project_id='".$project_id."' where tbl_lead_user_id='".$lead_id."'";
                            mysqli_query($conn, $sql_update);
                        }
                        
				    }
				    
				    
				    
				    // Send SMS to assigned user
                    $lead_name = $_POST['lead_name'];        // Example: "Kamal Tomar"
                    $project_name =getproject_name($msg_project_id);
                    $assigned_user = get_assigned_user_name($_POST['assigned_user']);                // Example: "Alice"
                    $mobile_number = get_assigned_user_mobile($_POST['assigned_user']);;         // Make sure to include country code without '+'
                    
                    // Compose the message EXACTLY as per template
                    //$message = "Hi, you have received a new lead - $lead_name for $project_name assigned to $assigned_user Vbuzz";
                    $message = "Hi, you have received a new lead - $lead_name for $project_name assigned to $assigned_user Vbuzz";
                    
                    // Build API URL with proper encoding
                    $sms_url = "http://sms.wishsolution.com/api/sms/SendSMS.aspx?" . http_build_query([
                        'usr' => 'Vbuzz',
                        'key' => '9374CC90-6932-4B5C-B2C1-5C7B13DF96BA',
                        'smstype' => 'TextSMS',
                        'to' => $mobile_number,
                        'msg' => $message,
                        'rout' => 'Transactional',
                        'from' => 'VBuzzz',
                        'templateid' => '1607100000000347990'
                    ]);
                    
                    // Send SMS using cURL
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $sms_url);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    $response = curl_exec($ch);
                    
                    // Handle errors
                    if (curl_errno($ch)) {
                        echo 'cURL error: ' . curl_error($ch);
                    } else {
                        echo 'SMS API Response: ' . $response;
                    }
                    curl_close($ch);

                    
                    // Send sms to Admin
                    // Get all active admins
                    $sql = "SELECT name, mobile_no FROM tbl_invite_user WHERE role='ADMIN' and status='ACTIVE'";  // Update role condition if needed
                    $result = $conn->query($sql);
                    
                    if ($result->num_rows > 0) {
                        // Loop through all admins
                        while ($row = $result->fetch_assoc()) {
                            //$assigned_user = $row['name'];
                            $mobile_number = $row['mobile_no'];  // Ensure mobile includes country code
                    
                            // Compose message (match template exactly)
                            $message = "Hi, you have received a new lead - $lead_name for $project_name assigned to $assigned_user Vbuzz";
                    
                            // Build SMS API URL
                            $sms_url = "http://sms.wishsolution.com/api/sms/SendSMS.aspx?" . http_build_query([
                                'usr' => 'Vbuzz',
                                'key' => '9374CC90-6932-4B5C-B2C1-5C7B13DF96BA',
                                'smstype' => 'TextSMS',
                                'to' => $mobile_number,
                                'msg' => $message,
                                'rout' => 'Transactional',
                                'from' => 'VBuzzz',
                                'templateid' => '1607100000000347990'
                            ]);
                    
                            // Send SMS via cURL
                            $ch = curl_init();
                            curl_setopt($ch, CURLOPT_URL, $sms_url);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                            $response = curl_exec($ch);
                    
                            // Check for errors
                            if (curl_errno($ch)) {
                               // echo 'Error sending to ' . $assigned_user . ': ' . curl_error($ch) . "<br>";
                            } else {
                                //echo 'SMS sent to ' . $assigned_user . ': ' . $response . "<br>";
                            }
                            curl_close($ch);
                        }
                    } else {
                        echo "No admin users found.";
                    }
                    
                    $conn->close();



				    // $sms_url = "http://sms.wishsolution.com/api/sms/SendSMS.aspx?usr=Vbuzz&key=9374CC90-6932-4B5C-B2C1-5C7B13DF96BA&smstype=TextSMS&to=9625471128&
				    // msg=Hi, you have received a new lead - {var} for {var} assigned to {var} Vbuzz&rout=Transactional&from=VBuzzz&templateid=1607100000000347990";

				    // Use file_get_contents or cURL to make the API request
				    // $response = file_get_contents($sms_url);

				    // // Optional: Log the response or handle any errors
				    // if ($response === FALSE) {
				    //     // Handle error if needed
				    //     echo "Error sending SMS.";
				    // }
				   
				    
					echo "<script language='javascript'>
						Swal.fire({
							title: 'Success!',
							text: 'Your request has been completed.',
							icon: 'success',
							confirmButtonClass: 'btn btn-primary w-xs mt-2',
							buttonsStyling: false,
							showCloseButton: false
						}).then(function() {
							window.location.href = 'dashboard-manager.php';
						});
					  </script>";
					  exit;
				}else{
					$sql=mysqli_query($conn,"DELETE FROM tbl_lead_user_profile WHERE tbl_lead_user_profile_id='".$user_profile_id."'");
					echo "<script language='javascript'>
						Swal.fire({
							title: 'Oops...!',
							text: 'Requested Incomplete Please Try Again!...',
							icon: 'error',
							confirmButtonClass: 'btn btn-primary w-xs mt-2',
							buttonsStyling: false,
							showCloseButton: false
						}).then(function() {
							window.location.href = 'dashboard-manager.php';
						});
					  </script>";
					  exit; 
				}
			}
		}else{
			$check_profile=mysqli_fetch_array(mysqli_query($conn,"Select tbl_lead_user_profile_id,tbl_lead_user_profile_dup_count from tbl_lead_user_profile where 1 and tbl_lead_user_profile_flag=0 and tbl_lead_user_profile_mobile='".$_POST['lead_mobile']."'"));
			$source_name=get_source_name($_POST['lead_source']);
			if($_POST['city']==''){
			    $_POST['city']=0;
			}
			$check_lead=mysqli_fetch_array(mysqli_query($conn,"Select * from tbl_lead_user where 1 and tbl_lead_user_profile_id= '".$check_profile['tbl_lead_user_profile_id']."'"));
			
		    //$sql="insert into tbl_lead_user set tbl_lead_user_profile_id='".$check_profile['tbl_lead_user_profile_id']."',tbl_lead_user_mobile='".$_POST['lead_mobile']."',tbl_lead_user_alt_mobile='".$_POST['alt_lead_mobile']."',tbl_lead_user_assigned_date='".date('Y-m-d H:i:s')."',tbl_lead_user_source_id='".$_POST['lead_source']."',tbl_lead_user_source_name='".$source_name."',tbl_lead_user_assigned_user_id='".$_POST['assigned_user']."',tbl_lead_user_regdate='".date('Y-m-d')."',tbl_lead_user_cdate='".date('Y-m-d H:i:s')."',tbl_lead_user_flag=0,tbl_lead_user_city_id='".$_POST['city']."',tbl_lead_user_cuser='ADMIN'";
			//$lead_result=mysqli_query($conn,$sql);
			$lead_result=true;
			//$lead_id=$conn->insert_id;
			$lead_id=$check_lead['tbl_lead_user_id'];
			if($lead_result){
			    $dup_count=$check_profile['tbl_lead_user_profile_dup_count']+1;
			    $update_dup_count_sql="Update tbl_lead_user_profile SET tbl_lead_user_profile_dup_count='".$dup_count."' WHERE tbl_lead_user_profile_id='".$check_profile['tbl_lead_user_profile_id']."'";
			    $update_user_profile_sql=mysqli_query($conn,$update_dup_count_sql);
			    if (isset($_POST['project_name']) && is_array($_POST['project_name'])) {
                    $project_ids = $_POST['project_name'];
                    // Insert selected projects into database
                    foreach ($project_ids as $project_id) {
                        $sql = "INSERT INTO tbl_lead_user_projects (tbl_lead_user_id, tbl_lead_user_prj_id) VALUES ('$lead_id', '$project_id')";
                        mysqli_query($conn, $sql);
                        $msg_project_id = $project_id;
                        $sql_update="UPDATE tbl_lead_user SET tbl_lead_user_dup_project_id='".$project_id."' where tbl_lead_user_id='".$lead_id."'";
                        mysqli_query($conn, $sql_update);
                    }
                    
			    }
			     //$sms_url = "http://pertinaxsolution.com/api/mt/SendSMS?user=Vbuzz%20Infra&password=Pert1236&senderid=VIEBRO&channel=Trans&DCS=0&flashsms=0&number=8076631024&text=%20Payye%20SAROJINI%20NAGAR%20maiPre-leased%20food%20court%20spacesBilkul%20Metro%20Station%20ke%20passSath%20mein%20paye%208%%20ki%20lease%20guaranteeCall:7428326363VIBRO&route=13&Peid=1201161491443489542&DLTTemplateId=1007787645328434291";

				    // // Use file_get_contents or cURL to make the API request
				    // $response = file_get_contents($sms_url);
				// Send SMS to assigned user
                    $lead_name = $_POST['lead_name'];        // Example: "Kamal Tomar"
                    $project_name =getproject_name($msg_project_id);
                    $assigned_user = get_assigned_user_name($_POST['assigned_user']);                // Example: "Alice"
                    $mobile_number = get_assigned_user_mobile($_POST['assigned_user']);;         // Make sure to include country code without '+'
                    
                    // Compose the message EXACTLY as per template
                    //$message = "Hi, you have received a new lead - $lead_name for $project_name assigned to $assigned_user Vbuzz";
                    $message = "Hi, you have received a new lead - $lead_name for $project_name assigned to $assigned_user Vbuzz";
                    
                    // Build API URL with proper encoding
                    $sms_url = "http://sms.wishsolution.com/api/sms/SendSMS.aspx?" . http_build_query([
                        'usr' => 'Vbuzz',
                        'key' => '9374CC90-6932-4B5C-B2C1-5C7B13DF96BA',
                        'smstype' => 'TextSMS',
                        'to' => $mobile_number,
                        'msg' => $message,
                        'rout' => 'Transactional',
                        'from' => 'VBuzzz',
                        'templateid' => '1607100000000347990'
                    ]);
                    
                    // Send SMS using cURL
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $sms_url);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    $response = curl_exec($ch);
                    
                    // Handle errors
                    if (curl_errno($ch)) {
                        echo 'cURL error: ' . curl_error($ch);
                    } else {
                        echo 'SMS API Response: ' . $response;
                    }
                    curl_close($ch);

                    
                    // Send sms to Admin
                    // Get all active admins
                    $sql = "SELECT name, mobile_no FROM tbl_invite_user WHERE role='ADMIN' and status='ACTIVE'";  // Update role condition if needed
                    $result = $conn->query($sql);
                    
                    if ($result->num_rows > 0) {
                        // Loop through all admins
                        while ($row = $result->fetch_assoc()) {
                            //$assigned_user = $row['name'];
                            $mobile_number = $row['mobile_no'];  // Ensure mobile includes country code
                    
                            // Compose message (match template exactly)
                            $message = "Hi, you have received a new lead - $lead_name for $project_name assigned to $assigned_user Vbuzz";
                    
                            // Build SMS API URL
                            $sms_url = "http://sms.wishsolution.com/api/sms/SendSMS.aspx?" . http_build_query([
                                'usr' => 'Vbuzz',
                                'key' => '9374CC90-6932-4B5C-B2C1-5C7B13DF96BA',
                                'smstype' => 'TextSMS',
                                'to' => $mobile_number,
                                'msg' => $message,
                                'rout' => 'Transactional',
                                'from' => 'VBuzzz',
                                'templateid' => '1607100000000347990'
                            ]);
                    
                            // Send SMS via cURL
                            $ch = curl_init();
                            curl_setopt($ch, CURLOPT_URL, $sms_url);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                            $response = curl_exec($ch);
                    
                            // Check for errors
                            if (curl_errno($ch)) {
                               // echo 'Error sending to ' . $assigned_user . ': ' . curl_error($ch) . "<br>";
                            } else {
                                //echo 'SMS sent to ' . $assigned_user . ': ' . $response . "<br>";
                            }
                            curl_close($ch);
                        }
                    } else {
                        echo "No admin users found.";
                    }
                    
                    $conn->close();
				    
				    
				echo "<script language='javascript'>
					Swal.fire({
						title: 'Success!',
						text: 'Your request has been completed.',
						icon: 'success',
						confirmButtonClass: 'btn btn-primary w-xs mt-2',
						buttonsStyling: false,
						showCloseButton: false
					}).then(function() {
						window.location.href = 'dashboard-manager.php';
					});
				  </script>";
				  exit; 
			}else{
				echo "<script language='javascript'>
					Swal.fire({
						title: 'Oops...!',
						text: 'Requested Incomplete Please Try Again!...',
						icon: 'error',
						confirmButtonClass: 'btn btn-primary w-xs mt-2',
						buttonsStyling: false,
						showCloseButton: false
					}).then(function() {
						window.location.href = 'dashboard-manager.php';
					});
				  </script>";
				  exit;
			}
		}
	}
}

?>

<script>
$(document).ready(function() {
    // Handle click on Not Connected link
    $(document).on('click', '.not-connected-link', function() {
        var leadName = $(this).data('lead-name');
        var leadId = $(this).data('lead-id');
        console.log(leadName,leadId)
        $('#notConnectedRightOffcanvas #lead_name').val(leadName);
        $('#notConnectedRightOffcanvas #lead_id').val(leadId);
    });
    // Handle click on In Progress link
    $(document).on('click', '.in-progress-link', function() {
        var leadName = $(this).data('lead-name');
        var leadId = $(this).data('inp-lead-id');
        console.log(leadName,leadId)
        $('#InProgressRightOffcanvas #inp_lead_name').val(leadName);
        $('#InProgressRightOffcanvas #inp_lead_id').val(leadId);
    });
    
    // Handle click on SV Scheduled link
    $(document).on('click', '.sv-scheduled-link', function () {
        var leadName = $(this).data('lead-name');
        var leadId = $(this).data('svs-lead-id');
        $('#svScheduledRightOffcanvas #svs_lead_name').val(leadName);
        $('#svScheduledRightOffcanvas #svs_lead_id').val(leadId);
    
        $.ajax({
            url: 'selected_projects_ajax.php',
            type: 'POST',
            data: { lead_id: leadId },
            dataType: 'json',
            success: function (response) {
                // Extract project names for display
                var projectNames = response.map(project => project.tbl_lead_user_projects_name);
                $('#svs_project_display').val(projectNames.join(', ')); // Show project names
            
                // Clear and add new hidden inputs with project IDs
                $('#hiddenProjectInputs').empty();
                response.forEach(function (project) {
                    var hiddenInput = $('<input>')
                        .attr('type', 'hidden')
                        .attr('name', 'svs_project_name[]')
                        .attr('value', project.tbl_lead_user_prj_id);
            
                    $('#hiddenProjectInputs').append(hiddenInput);
                });
            },
            error: function () {
                console.error('Failed to fetch projects.');
            }
        });
    });

    // Handle click on SV Completed link
    $(document).on('click', '.sv-completed-link', function() {
        var leadName = $(this).data('lead-name');
        var leadId = $(this).data('svc-lead-id');
        $('#svCompletedRightOffcanvas #svc_lead_name').val(leadName);
        $('#svCompletedRightOffcanvas #svc_lead_id').val(leadId);
        $.ajax({
            url: 'selected_projects_ajax.php',
            type: 'POST',
            data: { lead_id: leadId },
            dataType: 'json',
            success: function (response) {
                // Extract project names for display
                var projectNames = response.map(project => project.tbl_lead_user_projects_name);
                $('#svc_project_display').val(projectNames.join(', ')); // Show project names
            
                // Clear and add new hidden inputs with project IDs
                $('#hiddensvcProjectInputs').empty();
                response.forEach(function (project) {
                    var hiddenInput = $('<input>')
                        .attr('type', 'hidden')
                        .attr('name', 'svc_project_name[]')
                        .attr('value', project.tbl_lead_user_prj_id);
            
                    $('#hiddensvcProjectInputs').append(hiddenInput);
                });
            },
            error: function () {
                console.error('Failed to fetch projects.');
            }
        });
    });
    // Handle click on EOI Completed link
    $(document).on('click', '.eoi-completed-link', function() {
        var leadName = $(this).data('lead-name');
        var leadId = $(this).data('eoi-lead-id');
        $('#eoiCompletedRightOffcanvas #eoi_lead_name').val(leadName);
        $('#eoiCompletedRightOffcanvas #eoi_lead_id').val(leadId);
        $.ajax({
            url: 'selected_projects_ajax.php',
            type: 'POST',
            data: { lead_id: leadId },
            dataType: 'json',
            success: function (response) {
                // Extract project names for display
                var projectNames = response.map(project => project.tbl_lead_user_projects_name);
                $('#eoi_project_display').val(projectNames.join(', ')); // Show project names
            
                // Clear and add new hidden inputs with project IDs
                $('#hiddeneoiProjectInputs').empty();
                response.forEach(function (project) {
                    var hiddenInput = $('<input>')
                        .attr('type', 'hidden')
                        .attr('name', 'eoi_project_name[]')
                        .attr('value', project.tbl_lead_user_prj_id);
            
                    $('#hiddeneoiProjectInputs').append(hiddenInput);
                });
            },
            error: function () {
                console.error('Failed to fetch projects.');
            }
        });
    });
    // Handle click on Booking Completed link
    $(document).on('click', '.booking-completed-link', function() {
        var leadName = $(this).data('lead-name');
        var leadId = $(this).data('booking-lead-id');
        $('#bookingCompletedRightOffcanvas #booking_lead_name').val(leadName);
        $('#bookingCompletedRightOffcanvas #booking_lead_id').val(leadId);booking_lead_id
    });
    // Handle click on Dead lead link
    $(document).on('click', '.dead-link', function() {
        var leadName = $(this).data('lead-name');
        var leadId = $(this).data('dead-lead-id');
        $('#deadRightOffcanvas #dead_lead_name').val(leadName);
        $('#deadRightOffcanvas #dead_lead_id').val(leadId);
    });
});
</script>
<script>
    function isFutureDateTimeValid(dateInput,timeInput) {
        const selectedDate = dateInput.value;
        const selectedTime = timeInput.value;
    
        if (!selectedDate || !selectedTime) {
            return false; // No date or time selected
        }
    
        const selectedDateTime = new Date(`${selectedDate}T${selectedTime}`);
        const now = new Date();
    
        // Compare the selected date and time with current date and time
        return selectedDateTime > now;
    }

</script>
<script>
// Not Connected Form Submission Validation
function validateNotConnectedForm() {
    
    var followupDate = document.forms["notConnectedForm"]["nc_followup_date"].value;
    var followupTime = document.forms["notConnectedForm"]["nc_followup_time"].value;
    var intent = document.forms["notConnectedForm"]["nc_intent"].value;
    var reason = document.forms["notConnectedForm"]["nc_reason"].value;
    var errorMessage = "";

    if (followupDate == "") {
        errorMessage += "Followup Date is required.\n";
    }
    if (followupTime == "") {
        errorMessage += "Followup Time is required.\n";
    }
    if (intent == "") {
        errorMessage += "Intent is required.\n";
    }
    if (reason == "") {
        errorMessage += "Reason is required.\n";
    }

    if (errorMessage != "") {
        alert(errorMessage);
        return false;
    }
    return true;
}
</script>

<?php
// // Not Connected Form Submission 
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'not_connected' && isset($_POST['not_connected_form'])) {
    $lead_id = $_POST['lead_id'];
    $lead_name = $_POST['lead_name'];
    $followup_date = $_POST['nc_followup_date'];
    $followup_time = $_POST['nc_followup_time'];
    $datetime = $followup_date . ' ' . $followup_time;
    $formatted_datetime = date('Y-m-d H:i:s', strtotime($datetime));
    $intent = $_POST['nc_intent'];
    $reason = $_POST['nc_reason'];
    $comments = $_POST['nc_comments'];
    $edate=date('Y-m-d');
    $etime=date('H:i:s');
    $euser='Admin';
    $cdate=date('Y-m-d H:i:s');
    $project_id=get_lead_project_id($lead_id);
    
    $sql = "UPDATE tbl_lead_user SET 
            tbl_lead_user_intent = '$intent',
            tbl_lead_user_edate = '$edate',
            tbl_lead_user_etime = '$etime',
            tbl_lead_user_euser = '$euser',
            tbl_lead_user_fdate = '$formatted_datetime',
            tbl_lead_user_reason = '$reason',
            tbl_lead_user_status = 'Not Connected'
        WHERE tbl_lead_user_id  = '$lead_id'";
    if(mysqli_query($conn, $sql)) {
        // Insert followup data
        // $lead=mysqli_fetch_array(mysqli_query($conn,"select tbl_lead_user_id from tbl_lead_user where tbl_lead_user_mobile='$lead_id'"));
        // $lead_id=$lead['tbl_lead_user_id'];
     $sqlf = "INSERT INTO tbl_subfollowup SET 
                tbl_subfollowup_status_id = 1,
                tbl_subfollowup_status_name = 'Not Connected',
                tbl_lead_user_id = '$lead_id',
                tbl_subfollowup_date = '$formatted_datetime',
                tbl_subfollowup_intent = '$intent',
                tbl_subfollowup_reason = '$reason',
                tbl_subfollowup_comment = '$comments',
                tbl_subfollowup_cdate = '$cdate',
                tbl_subfollowup_project_id = $project_id,
                tbl_subfollowup_flag = 0";
         if(mysqli_query($conn, $sqlf)) {
            
            $project_name =getproject_name($project_id);
            $ass_user_id = get_assigned_user($lead_id);
            $assigned_user = get_assigned_user_name($ass_user_id);                // Example: "Alice"
            $mobile_number = get_assigned_user_mobile($ass_user_id);;         // Make sure to include country code without '+'
           // $mobile_number=9625471128;
            
            // Compose the message EXACTLY as per template
            //$message = "Hi, you have received a new lead - $lead_name for $project_name assigned to $assigned_user Vbuzz";
            //$message = "You have a followup with $lead_name at $followup_time, $followup_date for $project_name Vbuzz";
            //send_sms_site_followup($mobile_number,$message);
            $followup_type = "Not Connected";
            $message = "You have a followup with $lead_name at $followup_time,$followup_date for $project_name Vbuzz";
            $stmt = $conn->prepare("INSERT INTO scheduled_sms (mobile_number, message, followup_type, scheduled_datetime) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("ssss", $mobile_number, $message, $followup_type, $formatted_datetime);
            $stmt->execute(); 
           
            echo "<script>
                Swal.fire({
                    title: 'Success!',
                    text: 'Followup created successfully.',
                    icon: 'success',
                    confirmButtonClass: 'btn btn-primary w-xs mt-2',
                    buttonsStyling: false,
                    showCloseButton: false
                }).then(function() {
                    window.location.href = 'dashboard-manager.php';
                });
            </script>";
        } else {
            echo "<script>
                Swal.fire({
                    title: 'Error!',
                    text: 'Failed to create followup. Please try again.',
                    icon: 'error',
                    confirmButtonClass: 'btn btn-primary w-xs mt-2',
                    buttonsStyling: false,
                    showCloseButton: false
                });
            </script>";
        }
        exit;
    } else {
        echo "<script>
            Swal.fire({
                title: 'Error!',
                text: 'Failed to create followup. Please try again.',
                icon: 'error',
                confirmButtonClass: 'btn btn-primary w-xs mt-2',
                buttonsStyling: false,
                showCloseButton: false
            });
        </script>";
    }
    exit;
    
}
?>
<script>
// In Progress Form Submission Validation
function validateInProgressForm() {
    var followupDate = document.forms["inProgressForm"]["inp_followup_date"].value;
    var followupTime = document.forms["inProgressForm"]["inp_followup_time"].value;
    var intent = document.forms["inProgressForm"]["inp_intent"].value;
    //var reason = document.forms["inProgressForm"]["inp_reason"].value;
    var errorMessage = "";

    if (followupDate == "") {
        errorMessage += "Followup Date is required.\n";
    }
    if (followupTime == "") {
        errorMessage += "Followup Time is required.\n";
    }
    if (intent == "") {
        errorMessage += "Intent is required.\n";
    }
    // if (reason == "") {
    //     errorMessage += "Reason is required.\n";
    // }

    if (errorMessage != "") {
        alert(errorMessage);
        return false;
    }
    return true;
}
</script>

<?php
// In Progress Form Submission 
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'in_progress' && isset($_POST['in_progress_form'])) {
    $lead_id = $_POST['inp_lead_id'];
    $lead_name = $_POST['inp_lead_name'];
    $followup_date = $_POST['inp_followup_date'];
    $followup_time = $_POST['inp_followup_time'];
    $datetime = $followup_date . ' ' . $followup_time;
    $formatted_datetime = date('Y-m-d H:i:s', strtotime($datetime));
    $intent = $_POST['inp_intent'];
   // $reason = $_POST['inp_reason'];
    $comments = $_POST['inp_comments'];
    $edate=date('Y-m-d');
    $etime=date('H:i:s');
    $euser='Admin';
    $cdate=date('Y-m-d H:i:s');
    $project_id=get_lead_project_id($lead_id);
    
    echo $sql = "UPDATE tbl_lead_user SET 
            tbl_lead_user_intent = '$intent',
            tbl_lead_user_edate = '$edate',
            tbl_lead_user_etime = '$etime',
            tbl_lead_user_euser = '$euser',
            tbl_lead_user_fdate = '$formatted_datetime',
            tbl_lead_user_status = 'In Progress'
        WHERE tbl_lead_user_id  = '$lead_id'";
    if(mysqli_query($conn, $sql)) {
        // Insert followup data
        // $lead=mysqli_fetch_array(mysqli_query($conn,"select tbl_lead_user_id from tbl_lead_user where tbl_lead_user_mobile='$lead_id'"));
        // $lead_id=$lead['tbl_lead_user_id'];
         echo $sqlf = "INSERT INTO tbl_subfollowup SET 
                tbl_subfollowup_status_id = 2,
                tbl_subfollowup_status_name = 'In Progress',
                tbl_lead_user_id = '$lead_id',
                tbl_subfollowup_date = '$formatted_datetime',
                tbl_subfollowup_intent = '$intent',
                tbl_subfollowup_comment = '$comments',
                tbl_subfollowup_cdate = '$cdate',
                tbl_subfollowup_project_id = $project_id,
                tbl_subfollowup_flag = 0";
         if(mysqli_query($conn, $sqlf)) {
             
            $project_name =getproject_name($project_id);
            $ass_user_id = get_assigned_user($lead_id);
            $assigned_user = get_assigned_user_name($ass_user_id);                // Example: "Alice"
            $mobile_number = get_assigned_user_mobile($ass_user_id);         // Make sure to include country code without '+'
            $followup_type = "In Progress";
           //$mobile_number =9625471128;
            // Compose the message EXACTLY as per template
            //$message = "Hi, you have received a new lead - $lead_name for $project_name assigned to $assigned_user Vbuzz";
            $message = "You have a followup with $lead_name at $followup_time,$followup_date for $project_name Vbuzz";
            $stmt = $conn->prepare("INSERT INTO scheduled_sms (mobile_number, message, followup_type, scheduled_datetime) VALUES (?, ?, ?,?)");
            $stmt->bind_param("ssss", $mobile_number, $message, $followup_type, $formatted_datetime);
            $stmt->execute(); 
            
            //send_sms_inp($mobile_number,$message);
            
            echo "<script>
                Swal.fire({
                    title: 'Success!',
                    text: 'Followup created successfully.',
                    icon: 'success',
                    confirmButtonClass: 'btn btn-primary w-xs mt-2',
                    buttonsStyling: false,
                    showCloseButton: false
                }).then(function() {
                    window.location.href = 'dashboard-manager.php';
                });
            </script>";
        } else {
            echo "<script>
                Swal.fire({
                    title: 'Error!',
                    text: 'Failed to create followup. Please try again.',
                    icon: 'error',
                    confirmButtonClass: 'btn btn-primary w-xs mt-2',
                    buttonsStyling: false,
                    showCloseButton: false
                });
            </script>";
        }
        exit;
    } else {
        echo "<script>
            Swal.fire({
                title: 'Error!',
                text: 'Failed to create followup. Please try again.',
                icon: 'error',
                confirmButtonClass: 'btn btn-primary w-xs mt-2',
                buttonsStyling: false,
                showCloseButton: false
            });
        </script>";
    }
    exit;
    
}
?>
<script>
// SV Scheduled Form Submission Validation
function validateSVScheduledForm() {
    var svfollowupDate = document.forms["svScheduledForm"]["svs_followup_date_sv"].value;
    var svfollowupTime = document.forms["svScheduledForm"]["svs_followup_time_sv"].value;
    var typeOfSite = document.forms["svScheduledForm"]["svs_OnVideo"].value;
    var projectName = document.forms["svScheduledForm"]["svs_project_name"].value;
    var intent = document.forms["svScheduledForm"]["svs_intent"].value;
    var followupDate = document.forms["svScheduledForm"]["svs_followup_date"].value;
    var followupTime = document.forms["svScheduledForm"]["svs_followup_time"].value;
    var errorMessage = "";

    if (svfollowupDate == "") {
        errorMessage += "Site visit followup Date is required.\n";
    }
    if (svfollowupTime == "") {
        errorMessage += "Site visit followup Time is required.\n";
    }
    if (typeOfSite == "") {
        errorMessage += "Type of site visit is required.\n";
    }
    if (projectName == "") {
        errorMessage += "Project is required.\n";
    }
    if (intent == "") {
        errorMessage += "Intent is required.\n";
    }
    if (followupDate == "") {
        errorMessage += "followup Date is required.\n";
    }
    if (followupTime == "") {
        errorMessage += "followup Time is required.\n";
    }

    if (errorMessage != "") {
        alert(errorMessage);
        return false;
    }
    return true;
}
</script>

<?php
// SV Scheduled Form Submission 
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'sv_scheduled' && isset($_POST['sv_scheduled_form'])) {
    $lead_id = $_POST['svs_lead_id'];
    $lead_name = $_POST['svs_lead_name'];
    $followup_date = $_POST['svs_followup_date'];
    $followup_time = $_POST['svs_followup_time'];
    $datetime = $followup_date . ' ' . $followup_time;
    $formatted_datetime = date('Y-m-d H:i:s', strtotime($datetime));
    $followup_date_sv = $_POST['svs_followup_date_sv'];
    $followup_time_sv = $_POST['svs_followup_time_sv'];
    $datetime_sv = $followup_date_sv . ' ' . $followup_time_sv;
    $formatted_datetime_sv = date('Y-m-d H:i:s', strtotime($datetime_sv));
    $intent = $_POST['svs_intent'];
    $comments = $_POST['svs_comments'];
    $type_sv = $_POST['svs_OnVideo'];
    $edate=date('Y-m-d');
    $etime=date('H:i:s');
    $euser='Admin';
    $cdate=date('Y-m-d H:i:s');
    $project_id=get_lead_project_id($lead_id);
    
    $sql = "UPDATE tbl_lead_user SET 
            tbl_lead_user_intent = '$intent',
            tbl_lead_user_edate = '$edate',
            tbl_lead_user_etime = '$etime',
            tbl_lead_user_euser = '$euser',
            tbl_lead_user_fdate = '$formatted_datetime',
            tbl_lead_user_status = 'SV Scheduled',
            tbl_lead_user_sv_date = '$formatted_datetime_sv',
            tbl_lead_user_sv_type = '$type_sv'
        WHERE tbl_lead_user_id  = '$lead_id'";
    if(mysqli_query($conn, $sql)) {
        // Insert followup data
        // $lead=mysqli_fetch_array(mysqli_query($conn,"select tbl_lead_user_id from tbl_lead_user where tbl_lead_user_mobile='$lead_id'"));
        // $lead_id=$lead['tbl_lead_user_id'];
         $sqlf = "INSERT INTO tbl_subfollowup SET 
                tbl_subfollowup_status_id = 3,
                tbl_subfollowup_status_name = 'SV Scheduled',
                tbl_lead_user_id = '$lead_id',
                tbl_subfollowup_date = '$formatted_datetime',
                tbl_subfollowup_intent = '$intent',
                tbl_subfollowup_comment = '$comments',
                tbl_subfollowup_sv_scheduled_date = '$formatted_datetime_sv',
                tbl_subfollowup_sv_type = '$type_sv',
                tbl_subfollowup_cdate = '$cdate',
                tbl_subfollowup_project_id = $project_id,
                tbl_subfollowup_flag = 0";
         if(mysqli_query($conn, $sqlf)) {
            
            $project_name =getproject_name($project_id);
            $ass_user_id = get_assigned_user($lead_id);
            $assigned_user = get_assigned_user_name($ass_user_id);                // Example: "Alice"
            $mobile_number = get_assigned_user_mobile($ass_user_id);;         // Make sure to include country code without '+'
            
            // Compose the message EXACTLY as per template
            //$message = "Hi, you have received a new lead - $lead_name for $project_name assigned to $assigned_user Vbuzz";
           // $message = "You have a site visit scheduled with $lead_name at $followup_date_sv for $project_name Vbuzz";
            $followup_type ="SV Scheduledf";
            //send_sms_site_scheduled($mobile_number,$message);
            $message = "You have a followup with $lead_name at $followup_time,$followup_date for site visit scheduled at $followup_time_sv,$followup_date_sv for $project_name Vbuzz";
            $stmt = $conn->prepare("INSERT INTO scheduled_sms (mobile_number, message, followup_type, scheduled_datetime) VALUES (?, ?, ?,?)");
            $stmt->bind_param("ssss", $mobile_number, $message, $followup_type, $formatted_datetime);
            $stmt->execute(); 
            
            $followup_type ="SV Scheduled";
            $message1 = "You have a site visit scheduled with $lead_name at $followup_time_sv,$followup_date_sv for $project_name Vbuzz";
            $stmt1 = $conn->prepare("INSERT INTO scheduled_sms (mobile_number, message, followup_type, scheduled_datetime) VALUES (?, ?, ?,?)");
            $stmt1->bind_param("ssss", $mobile_number, $message1, $followup_type, $formatted_datetime_sv);
            $stmt1->execute(); 
            // $sql = "SELECT name, mobile_no FROM tbl_invite_user WHERE role='ADMIN' and status='ACTIVE'";  // Update role condition if needed
            // $result = $conn->query($sql);
            // if ($result->num_rows > 0) {
            // 	// Loop through all admins
            // 	while ($row = $result->fetch_assoc()) {
            // 		//$assigned_user = $row['name'];
            // 		$mobile_number = $row['mobile_no'];  // Ensure mobile includes country code
            
            // 		// Compose message (match template exactly)
            // 		$message = "You have a site visit scheduled with $lead_name at $sfollowup_time, $sfollowup_date for $project_name Vbuzz";
            
            // 		// Build SMS API URL
            // 		send_sms($mobile_number,$message);
            // 	}
            // } else {
            // 	echo "No admin users found.";
            // } 
            
            echo "<script>
                Swal.fire({
                    title: 'Success!',
                    text: 'Followup created successfully.',
                    icon: 'success',
                    confirmButtonClass: 'btn btn-primary w-xs mt-2',
                    buttonsStyling: false,
                    showCloseButton: false
                }).then(function() {
                    window.location.href = 'dashboard-manager.php';
                });
            </script>";
        } else {
            echo "<script>
                Swal.fire({
                    title: 'Error!',
                    text: 'Failed to create followup. Please try again.',
                    icon: 'error',
                    confirmButtonClass: 'btn btn-primary w-xs mt-2',
                    buttonsStyling: false,
                    showCloseButton: false
                });
            </script>";
        }
        exit;
    } else {
        echo "<script>
            Swal.fire({
                title: 'Error!',
                text: 'Failed to create followup. Please try again.',
                icon: 'error',
                confirmButtonClass: 'btn btn-primary w-xs mt-2',
                buttonsStyling: false,
                showCloseButton: false
            });
        </script>";
    }
    exit;
    
}
?>
<script>
// SV Completed Form Submission Validation
function validateSVCompletedForm() {
    var followupDate = document.forms["svCompletedForm"]["svc_followup_date"].value;
    var followupTime = document.forms["svCompletedForm"]["svc_followup_time"].value;
    var sfollowupDate = document.forms["svCompletedForm"]["svc_followup_date_sv"].value;
    var sfollowupTime = document.forms["svCompletedForm"]["svc_followup_time_sv"].value;
    var projectName = document.forms["svCompletedForm"]["svc_project_name"].value;
    var intent = document.forms["svCompletedForm"]["svc_intent"].value;
    var svType = document.forms["svCompletedForm"]["svc_OnVideo"].value;
    var duration = document.forms["svCompletedForm"]["svc_duration"].value;
    var errorMessage = "";

    if (followupDate == "") {
        errorMessage += "Followup Date is required.\n";
    }
    if (followupTime == "") {
        errorMessage += "Followup Time is required.\n";
    }
    if (sfollowupDate == "") {
        errorMessage += "Site visit Followup Date is required.\n";
    }
    if (sfollowupTime == "") {
        errorMessage += "Sit visit Followup Time is required.\n";
    }
    if (intent == "") {
        errorMessage += "Intent is required.\n";
    }
    if (svType == "") {
        errorMessage += "Type of site visit is required.\n";
    }
    if (duration == "") {
        errorMessage += "Site visit duration is required.\n";
    }

    if (errorMessage != "") {
        alert(errorMessage);
        return false;
    }
    return true;
}
</script>

<?php
// SV Completed Form Submission 
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'sv_completed' && isset($_POST['sv_completed_form'])) {
    $lead_id = $_POST['svc_lead_id'];
    $lead_name = $_POST['svc_lead_name'];
    $followup_date = $_POST['svc_followup_date'];
    $followup_time = $_POST['svc_followup_time'];
    $datetime = $followup_date . ' ' . $followup_time;
    $formatted_datetime = date('Y-m-d H:i:s', strtotime($datetime));
    $sfollowup_date = $_POST['svc_followup_date_sv'];
    $sfollowup_time = $_POST['svc_followup_time_sv'];
    $sdatetime = $sfollowup_date . ' ' . $sfollowup_time;
    $sformatted_datetime = date('Y-m-d H:i:s', strtotime($sdatetime));
    $intent = $_POST['svc_intent'];
    $project = $_POST['svc_project_name'];
    $duration = $_POST['svc_duration'];
    $sv_type= $_POST['svc_OnVideo'];
    $comments = $_POST['svc_comments'];
    $edate=date('Y-m-d');
    $etime=date('H:i:s');
    $euser='Admin';
    $cdate=date('Y-m-d H:i:s');
    $project_id=get_lead_project_id($lead_id);
    
    //sv Completed not befor sv scheduled
    $checkSVComp =mysqli_num_rows(mysqli_query($conn,"Select tbl_subfollowup_id from tbl_subfollowup where tbl_lead_user_id='".$lead_id."' AND tbl_subfollowup_status_name='SV Scheduled'"));
    if($checkSVComp >0){
        $sql = "UPDATE tbl_lead_user SET 
                tbl_lead_user_intent = '$intent',
                tbl_lead_user_edate = '$edate',
                tbl_lead_user_etime = '$etime',
                tbl_lead_user_euser = '$euser',
                tbl_lead_user_fdate = '$formatted_datetime',
                tbl_lead_user_sv_date = '$sformatted_datetime',
                tbl_lead_user_sv_duration = '$duration',
                tbl_lead_user_status = 'SV Completed'
            WHERE tbl_lead_user_id  = '$lead_id'";
        if(mysqli_query($conn, $sql)) {
            // Insert followup data
            // $lead=mysqli_fetch_array(mysqli_query($conn,"select tbl_lead_user_id from tbl_lead_user where tbl_lead_user_mobile='$lead_id'"));
            // $lead_id=$lead['tbl_lead_user_id'];
            $sqlf = "INSERT INTO tbl_subfollowup SET 
                    tbl_subfollowup_status_id = 4,
                    tbl_subfollowup_status_name = 'SV Completed',
                    tbl_lead_user_id = '$lead_id',
                    tbl_subfollowup_date = '$formatted_datetime',
                    tbl_subfollowup_sv_intent = '$intent',
                    tbl_subfollowup_comment = '$comments',
                    tbl_subfollowup_sv_comment = '$comments',
                    tbl_subfollowup_sv_scheduled_date = '$sformatted_datetime',
                    tbl_subfollowup_sv_type = '$sv_type',
                    tbl_subfollowup_cdate = '$cdate',
                    tbl_subfollowup_project_id = $project_id,
                    tbl_subfollowup_flag = 0";
            if(mysqli_query($conn, $sqlf)) {
                 
                $project_name =getproject_name($project_id);
                $ass_user_id = get_assigned_user($lead_id);
                $assigned_user = get_assigned_user_name($ass_user_id);                // Example: "Alice"
                //$mobile_number = get_assigned_user_mobile($ass_user_id);;         // Make sure to include country code without '+'
                
                // Compose the message EXACTLY as per template
                //$message = "Hi, you have received a new lead - $lead_name for $project_name assigned to $assigned_user Vbuzz";
                //$message = "Eoi completed with $lead_name at {time}, {date} for {project} by sales person{user}";
                $sql = "SELECT name, mobile_no FROM tbl_invite_user WHERE role='ADMIN' and status='ACTIVE'";  // Update role condition if needed
                $result = $conn->query($sql);
                if ($result->num_rows > 0) {
                	// Loop through all admins
                	while ($row = $result->fetch_assoc()) {
                		//$assigned_user = $row['name'];
                		$mobile_number = $row['mobile_no'];  // Ensure mobile includes country code
                
                		// Compose message (match template exactly)
                		$message = "site visit completed with $lead_name at $sfollowup_time, $sfollowup_date for $project_name by sales person $assigned_user VBuzz";
                        $followup_type = "SV Completed";
                		// Build SMS API URL
                		//send_sms_site_visit_completed($mobile_number,$message);
                		//$message = "You have a followup with $lead_name at $followup_time,$followup_date for $project_name Vbuzz";
                        $stmt = $conn->prepare("INSERT INTO scheduled_sms (mobile_number, message, followup_type, scheduled_datetime) VALUES (?, ?, ?,?)");
                        $stmt->bind_param("ssss", $mobile_number, $message, $followup_type, $formatted_datetime);
                        $stmt->execute(); 
                	}
                } else {
                	echo "No admin users found.";
                }
                 
                echo "<script>
                    Swal.fire({
                        title: 'Success!',
                        text: 'Followup created successfully.',
                        icon: 'success',
                        confirmButtonClass: 'btn btn-primary w-xs mt-2',
                        buttonsStyling: false,
                        showCloseButton: false
                    }).then(function() {
                        window.location.href = 'dashboard-manager.php';
                    });
                </script>";
            } else {
                echo "<script>
                    Swal.fire({
                        title: 'Error!',
                        text: 'Failed to create followup. Please try again.',
                        icon: 'error',
                        confirmButtonClass: 'btn btn-primary w-xs mt-2',
                        buttonsStyling: false,
                        showCloseButton: false
                    });
                </script>";
            }
        } else {
            echo "<script>
                Swal.fire({
                    title: 'Error!',
                    text: 'SV Completed is not done before SV Scheduled.Error! Occoured. ',
                    icon: 'error',
                    confirmButtonClass: 'btn btn-primary w-xs mt-2',
                    buttonsStyling: false,
                    showCloseButton: false
                });
            </script>";
        }
        exit;
    } else {
        echo "<script>
            Swal.fire({
                title: 'Error!',
                text: 'Failed to create followup. Please try again.',
                icon: 'error',
                confirmButtonClass: 'btn btn-primary w-xs mt-2',
                buttonsStyling: false,
                showCloseButton: false
            });
        </script>";
    }
    exit;
    
}
?>
<script>
// EOI Completed Form Submission Validation
function validateEoiCompletedForm() {
    var tokenDate = document.forms["eoiCompletedForm"]["eoi_token_date"].value;
    var tokenTime = document.forms["eoiCompletedForm"]["eoi_token_time"].value;
    var projectName = document.forms["eoiCompletedForm"]["eoi_project_name"].value;
    var tokenAmount = document.forms["eoiCompletedForm"]["eoi_token_amount"].value;
    var validityDate = document.forms["eoiCompletedForm"]["eoi_validity_date"].value;
    var unitPrice = document.forms["eoiCompletedForm"]["eoi_unit_price"].value;
    var unitNo = document.forms["eoiCompletedForm"]["eoi_unit_no"].value;
    var followupDate = document.forms["eoiCompletedForm"]["eoi_followup_date"].value;
    var followupTime = document.forms["eoiCompletedForm"]["eoi_followup_time"].value;
    var errorMessage = "";

    if (tokenDate == "") {
        errorMessage += "Token Date is required.\n";
    }
    if (tokenTime == "") {
        errorMessage += "Token Time is required.\n";
    }
    if (followupDate == "") {
        errorMessage += "Followup Date is required.\n";
    }
    if (followupTime == "") {
        errorMessage += "Followup Time is required.\n";
    }
    if (projectName == "") {
        errorMessage += "Project Name is required.\n";
    }
    if (tokenAmount == "") {
        errorMessage += "Token Amount is required.\n";
    }
    if (validityDate == "") {
        errorMessage += "Validity date is required.\n";
    }
    if (unitPrice == "") {
        errorMessage += "Unit price is required.\n";
    }
    if (unitNo == "") {
        errorMessage += "Unit no is required.\n";
    }

    if (errorMessage != "") {
        alert(errorMessage);
        return false;
    }
    return true;
}
</script>

<?php
// EOI Completed Form Submission 
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'eoi_completed' && isset($_POST['eoi_completed_form'])) {
    $lead_id = $_POST['eoi_lead_id'];
    $lead_name = $_POST['eoi_lead_name'];
    $followup_date = $_POST['eoi_followup_date'];
    $followup_time = $_POST['eoi_followup_time'];
    $datetime = $followup_date . ' ' . $followup_time;
    $formatted_datetime = date('Y-m-d H:i:s', strtotime($datetime));
    $token_date = $_POST['eoi_token_date'];
    $token_time = $_POST['eoi_token_time'];
    $datetimet = $token_date . ' ' . $token_time;
    $formatted_datetime_token = date('Y-m-d H:i:s', strtotime($datetimet));
    $validity_date = $_POST['eoi_validity_date'];
    $formatted_validity_date= date('Y-m-d', strtotime($validity_date));
    $project=$_POST['eoi_project_name'];
    $token_amount = $_POST['eoi_token_amount'];
    $unit_price = $_POST['eoi_unit_price'];
    $unit_no = $_POST['eoi_unit_no'];
    $comments = $_POST['eoi_comments'];
    $edate=date('Y-m-d');
    $etime=date('H:i:s');
    $euser='Admin';
    $cdate=date('Y-m-d H:i:s');
    $project_id=get_lead_project_id($lead_id);
    
    $sql = "UPDATE tbl_lead_user SET 
            tbl_lead_user_edate = '$edate',
            tbl_lead_user_etime = '$etime',
            tbl_lead_user_euser = '$euser',
            tbl_lead_user_eoi_date = '$formatted_datetime',
            tbl_lead_user_status = 'EOI Completed'
        WHERE tbl_lead_user_id  = '$lead_id'";
    if(mysqli_query($conn, $sql)) {
        // Insert followup data
        // $lead=mysqli_fetch_array(mysqli_query($conn,"select tbl_lead_user_id from tbl_lead_user where tbl_lead_user_mobile='$lead_id'"));
        // $lead_id=$lead['tbl_lead_user_id'];
        $sqlf = "INSERT INTO tbl_subfollowup SET 
                tbl_subfollowup_status_id = 7,
                tbl_subfollowup_status_name = 'EOI Completed',
                tbl_lead_user_id = '$lead_id',
                tbl_subfollowup_date = '$formatted_datetime',
                tbl_subfollowup_eoi_token_date = '$formatted_datetime_token',
                tbl_subfollowup_eoi_token_amount = '$token_amount',
                tbl_subfollowup_eoi_validity_date = '$formatted_validity_date',
                tbl_subfollowup_eoi_unit_price= '$unit_price',
                tbl_subfollowup_eoi_unit_no= '$unit_no',
                tbl_subfollowup_comment = '$comments',
                tbl_subfollowup_eoi_token_comment= '$comments',
                tbl_subfollowup_cdate = '$cdate',
                tbl_subfollowup_project_id = $project_id,
                tbl_subfollowup_flag = 0";
         if(mysqli_query($conn, $sqlf)) {
            
           // $lead_name = $_POST['lead_name'];        // Example: "Kamal Tomar"
            $project_name =getproject_name($project_id);
            $ass_user_id = get_assigned_user($lead_id);
            $assigned_user = get_assigned_user_name($ass_user_id);                // Example: "Alice"
            $mobile_number = get_assigned_user_mobile($ass_user_id);;         // Make sure to include country code without '+'
            
            // Compose the message EXACTLY as per template
            //$message = "Hi, you have received a new lead - $lead_name for $project_name assigned to $assigned_user Vbuzz";
            //$message = "Eoi completed with $lead_name at {time}, {date} for {project} by sales person{user}";
            $sql = "SELECT name, mobile_no FROM tbl_invite_user WHERE role='ADMIN' and status='ACTIVE'";  // Update role condition if needed
            $result = $conn->query($sql);
            if ($result->num_rows > 0) {
            	// Loop through all admins
            	while ($row = $result->fetch_assoc()) {
            		//$assigned_user = $row['name'];
            		$mobile_number = $row['mobile_no'];  // Ensure mobile includes country code
            
            		// Compose message (match template exactly)
            		$message = "Eoi completed with $lead_name at $followup_time, $followup_date for $project_name by sales person$assigned_user VBuzz";
            		$followup_type="EOI Completed";
                    //$message = "You have a followup with $lead_name at $followup_time,$followup_date for $project_name Vbuzz";
                    $stmt = $conn->prepare("INSERT INTO scheduled_sms (mobile_number, message, followup_type, scheduled_datetime) VALUES (?, ?, ?,?)");
                    $stmt->bind_param("ssss", $mobile_number, $message, $followup_type, $formatted_datetime);
                    $stmt->execute(); 
            		// Build SMS API URL
            		//send_sms_eoi($mobile_number,$message);
            	}
            } else {
            	echo "No admin users found.";
            }
            
            echo "<script>
                Swal.fire({
                    title: 'Success!',
                    text: 'Followup created successfully.',
                    icon: 'success',
                    confirmButtonClass: 'btn btn-primary w-xs mt-2',
                    buttonsStyling: false,
                    showCloseButton: false
                }).then(function() {
                    window.location.href = 'dashboard-manager.php';
                });
            </script>";
        } else {
            echo "<script>
                Swal.fire({
                    title: 'Error!',
                    text: 'Failed to create followup. Please try again.',
                    icon: 'error',
                    confirmButtonClass: 'btn btn-primary w-xs mt-2',
                    buttonsStyling: false,
                    showCloseButton: false
                });
            </script>";
        }
        exit;
    } else {
        echo "<script>
            Swal.fire({
                title: 'Error!',
                text: 'Failed to create followup. Please try again.',
                icon: 'error',
                confirmButtonClass: 'btn btn-primary w-xs mt-2',
                buttonsStyling: false,
                showCloseButton: false
            });
        </script>";
    }
    exit;
    
}
?>
<script>
// Booking Completed Form Submission Validation
function validateBookingCompletedForm() {
    
    var followupDate = document.forms["bookingCompletedForm"]["booking_followup_date"].value;
   
    var followupTime = document.forms["bookingCompletedForm"]["booking_followup_time"].value;
    //var bookingProject = document.forms["bookingCompletedForm"]["booking_project_name"].value;
    var purchase_price = document.forms["bookingCompletedForm"]["booking_purchase_price"].value;
    var amt_paid = document.forms["bookingCompletedForm"]["booking_amount_paid"].value;
    var unit_no = document.forms["bookingCompletedForm"]["booking_unit_no"].value;
    var errorMessage = "";

    if (followupDate == "") {
        errorMessage += "Followup Date is required.\n";
    }
    if (followupTime == "") {
        errorMessage += "Followup Time is required.\n";
    }
    // if (bookingProject == "") {
    //     errorMessage += "Project is required.\n";
    // }
    if (purchase_price == "") {
        errorMessage += "Purchase Price is required.\n";
    }
    if (amt_paid == "") {
        errorMessage += "Amount paid is required.\n";
    }
    if (unit_no == "") {
        errorMessage += "Unit no. is required.\n";
    }

    if (errorMessage != "") {
        alert(errorMessage);
        return false;
    }
    return true;
}
</script>

<?php
// Booking Completed Form Submission 
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'booking_completed' && isset($_POST['booking_completed_form'])) {
    $lead_id = $_POST['booking_lead_id'];
    $lead_name = $_POST['booking_lead_name'];
    $followup_date = $_POST['booking_followup_date'];
    $followup_time = $_POST['booking_followup_time'];
    $datetime = $followup_date . ' ' . $followup_time;
    $formatted_datetime = date('Y-m-d H:i:s', strtotime($datetime));
    //$project = $_POST['booking_project_name'];
    $purchase_price = $_POST['booking_purchase_price'];
    $booking_amt = $_POST['booking_amount_paid'];
    $unit_no = $_POST['booking_unit_no'];
    $comments = $_POST['booking_comments'];
    $edate=date('Y-m-d');
    $etime=date('H:i:s');
    $euser='Admin';
    $cdate=date('Y-m-d H:i:s');
    
    //Booking Completed not befor EOI Token
    $checkSVComp =mysqli_num_rows(mysqli_query($conn,"Select tbl_subfollowup_id from tbl_subfollowup where tbl_lead_user_id='".$lead_id."' AND tbl_subfollowup_status_name='EOI Completed'"));
    if($checkSVComp >0){
    
        $sql = "UPDATE tbl_lead_user SET 
                tbl_lead_user_edate = '$edate',
                tbl_lead_user_etime = '$etime',
                tbl_lead_user_euser = '$euser',
                tbl_lead_user_booking_date = '$formatted_datetime',
                tbl_lead_user_status = 'Booking Completed'
            WHERE tbl_lead_user_id  = '$lead_id'";
        if(mysqli_query($conn, $sql)) {
            // Insert followup data
            // $lead=mysqli_fetch_array(mysqli_query($conn,"select tbl_lead_user_id from tbl_lead_user where tbl_lead_user_mobile='$lead_id'"));
            // $lead_id=$lead['tbl_lead_user_id'];
            $sqlf = "INSERT INTO tbl_subfollowup SET 
                    tbl_subfollowup_status_id = 5,
                    tbl_subfollowup_status_name = 'Booking Completed',
                    tbl_lead_user_id = '$lead_id',
                    tbl_subfollowup_date = '$formatted_datetime',
                    tbl_subfollowup_booking_date = '$formatted_datetime',
                    tbl_subfollowup_booking_net_purchase_price = '$purchase_price',
                    tbl_subfollowup_booking_amt_paid = '$booking_amt',
                    tbl_subfollowup_booking_unit_no = '$unit_no',
                    tbl_subfollowup_comment = '$comments',
                    tbl_subfollowup_booking_comment = '$comments',
                    tbl_subfollowup_cdate = '$cdate',
                    tbl_subfollowup_flag = 0";
             if(mysqli_query($conn, $sqlf)) {
                echo "<script>
                    Swal.fire({
                        title: 'Success!',
                        text: 'Followup created successfully.',
                        icon: 'success',
                        confirmButtonClass: 'btn btn-primary w-xs mt-2',
                        buttonsStyling: false,
                        showCloseButton: false
                    }).then(function() {
                        window.location.href = 'dashboard-manager.php';
                    });
                </script>";
            } else {
                echo "<script>
                    Swal.fire({
                        title: 'Error!',
                        text: 'Failed to create followup. Please try again.',
                        icon: 'error',
                        confirmButtonClass: 'btn btn-primary w-xs mt-2',
                        buttonsStyling: false,
                        showCloseButton: false
                    });
                </script>";
            }
        } 
        exit;
     } else {
            echo "<script>
                Swal.fire({
                    title: 'Error!',
                    text: 'Booking Completed is not done before EOI Completed.Error! Occoured. ',
                    icon: 'error',
                    confirmButtonClass: 'btn btn-primary w-xs mt-2',
                    buttonsStyling: false,
                    showCloseButton: false
                });
            </script>";
        } 
    
    exit;
    
}
?>
<script>
// Dead Form Submission Validation
function validateDeadForm() {
   
    var reason = document.forms["deadForm"]["dead_reason"].value;
    var errorMessage = "";

    if (reason == "") {
        errorMessage += "Reason is required.\n";
    }

    if (errorMessage != "") {
        alert(errorMessage);
        return false;
    }
    return true;
}
</script>

<?php
// Dead Form Submission 
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'dead' && isset($_POST['dead_form'])) {
    $lead_id = $_POST['dead_lead_id'];
    $lead_name = $_POST['dead_lead_name'];
    $reason = $_POST['dead_reason'];
    $comments = $_POST['dead_comments'];
    $edate=date('Y-m-d');
    $etime=date('H:i:s');
    $euser='Admin';
    $cdate=date('Y-m-d H:i:s');
    
    $sql = "UPDATE tbl_lead_user SET 
            tbl_lead_user_edate = '$edate',
            tbl_lead_user_etime = '$etime',
            tbl_lead_user_euser = '$euser',
            tbl_lead_user_reason = '$reason',
            tbl_lead_user_status = 'Dead Lead'
        WHERE tbl_lead_user_id  = '$lead_id'";
    if(mysqli_query($conn, $sql)) {
        // Insert followup data
        // $lead=mysqli_fetch_array(mysqli_query($conn,"select tbl_lead_user_id from tbl_lead_user where tbl_lead_user_mobile='$lead_id'"));
        // $lead_id=$lead['tbl_lead_user_id'];
        $sqlf = "INSERT INTO tbl_subfollowup SET 
                tbl_subfollowup_status_id = 6,
                tbl_subfollowup_status_name = 'Dead Lead',
                tbl_lead_user_id = '$lead_id',
                tbl_subfollowup_reason = '$reason',
                tbl_subfollowup_comment = '$comments',
                tbl_subfollowup_cdate = '$cdate',
                tbl_subfollowup_flag = 0";
         if(mysqli_query($conn, $sqlf)) {
            echo "<script>
                Swal.fire({
                    title: 'Success!',
                    text: 'Followup created successfully.',
                    icon: 'success',
                    confirmButtonClass: 'btn btn-primary w-xs mt-2',
                    buttonsStyling: false,
                    showCloseButton: false
                }).then(function() {
                    window.location.href = 'dashboard-manager.php';
                });
            </script>";
        } else {
            echo "<script>
                Swal.fire({
                    title: 'Error!',
                    text: 'Failed to create followup. Please try again.',
                    icon: 'error',
                    confirmButtonClass: 'btn btn-primary w-xs mt-2',
                    buttonsStyling: false,
                    showCloseButton: false
                });
            </script>";
        }
        exit;
    } else {
        echo "<script>
            Swal.fire({
                title: 'Error!',
                text: 'Failed to create followup. Please try again.',
                icon: 'error',
                confirmButtonClass: 'btn btn-primary w-xs mt-2',
                buttonsStyling: false,
                showCloseButton: false
            });
        </script>";
    }
    exit;
    
}
?>

<script>
    // Declare globally
    let enableNewCheckboxSelection = false;
    let enableCheckboxSelection = false;
    let enabledeleteleadCheckboxSelection = false;

$(document).ready(function() {
    // Initialize only the new leads table on page load
    
    fetch('get-lead-counters.php')
      .then(res => res.json())
      .then(counterData => {
        // Update each tab label dynamically
        document.querySelector("a[href='#home'] span.d-none.d-sm-block").innerHTML = `All(${counterData.all})`;
        document.querySelector("a[href='#profile'] span.d-none.d-sm-block").innerHTML = `New(${counterData.new})`;
        document.querySelector("a[href='#messages'] span.d-none.d-sm-block").innerHTML = `Followup(${counterData.followup})`;
        document.querySelector("a[href='#svscheduled'] span.d-none.d-sm-block").innerHTML = `SV Scheduled(${counterData.svscheduled})`;
        document.querySelector("a[href='#svcompleted'] span.d-none.d-sm-block").innerHTML = `SV Completed(${counterData.svcompleted})`;
        document.querySelector("a[href='#bookingeois'] span.d-none.d-sm-block").innerHTML = `Booking/EOIs(${counterData.bookingeoi})`;
        document.querySelector("a[href='#dead'] span.d-none.d-sm-block").innerHTML = `Dead(${counterData.dead})`;
    });
    
    let enableNewCheckboxSelection = false;
    if (document.getElementById("table-gridjs")) {
         initializeAllTable();
        //initializeNewLeadsTable();
    }
    
    // Initialize other tables only when their respective tabs are clicked
    $('a[data-bs-toggle="tab"]').on('shown.bs.tab', function (e) {
        let target = $(e.target).attr("href");
        
        switch(target) {
            case "#home":
                if (!window.allTableInitialized) {
                    initializeAllTable();
                    window.allTableInitialized = true;
                }
                break;
            case "#profile":
                if (!window.allTableInitialized) {
                    initializeNewLeadsTable();
                    window.allTableInitialized = true;
                }
                break;
            case "#messages":
                if (!window.followupTableInitialized) {
                    initializefollowupTable();
                    window.followupTableInitialized = true;
                }
                break;
            case "#svscheduled":
                if (!window.svScheduledTableInitialized) {
                    initializeSVScheduledTable();
                    window.svScheduledTableInitialized = true;
                }
                break;
            case "#svcompleted":
                if (!window.svCompletedTableInitialized) {
                    initializeSVCompletedTable();
                    window.svCompletedTableInitialized = true;
                }
                break;
            case "#bookingeois":
                if (!window.bookingEOITableInitialized) {
                    initializeBookingEOITable();
                    window.bookingEOITableInitialized = true;
                }
                break;
            case "#dead":
                if (!window.deadLeadsTableInitialized) {
                    initializeDeadLeadsTable();
                    window.deadLeadsTableInitialized = true;
                }
                break;
        }
    });
});

// document.addEventListener('change', function(e) {
//     if (e.target && e.target.id === 'selectAllLeads') {
//         const isChecked = e.target.checked;
//         document.querySelectorAll('.lead-checkbox').forEach(checkbox => {
//             checkbox.checked = isChecked;
//         });
//     }
// });

// document.addEventListener('click', function (e) {
//     // Prevent sorting when clicking the "All" checkbox in header
//     if (e.target && e.target.id === 'selectAllLeads') {
//         e.stopPropagation(); // Stop the click from bubbling up to Grid.js
//     }
// });

// document.addEventListener('change', function (e) {
//     if (e.target && e.target.id === 'selectAllLeads') {
//         const isChecked = e.target.checked;
//         const checkboxes = document.querySelectorAll('.lead-checkbox');
//         checkboxes.forEach(checkbox => {
//             checkbox.checked = isChecked;
//         });
//     }
// });
if (performance.navigation.type === performance.navigation.TYPE_RELOAD) {
    fetch('unset-session.php')  // Calls your backend to unset the session variable
        .then(res => res.json())
        .then(data => console.log("Session cleared:", data));  // For debugging
}

let filters = {};

// Triggered when user clicks "Re-assign Leads" button
document.getElementById("openReassignCanvas").addEventListener("click", function () {
    enableCheckboxSelection = true;
    enableNewCheckboxSelection = true;
    filters = { selectedStatus: "reassignleads" };

    // Store the selectedStatus in session (using AJAX)
    fetch('store-session.php', {
        method: 'POST',
        body: JSON.stringify({ selectedStatus: "reassignleads" }),
        headers: { 'Content-Type': 'application/json' }
    })
    .then(response => response.json())
    .then(data => {
        console.log("Selected status stored in session:", data);
    })
    .catch(error => {
        console.error("Error storing selectedStatus in session:", error);
    });

    // Show the confirm button container
    document.getElementById("confirmReassignContainer").style.display = "block";

    // Reinitialize both tables with checkbox column
    initializeAllTable();
    initializeNewLeadsTable();

    // After short delay to let Grid.js finish rendering
    setTimeout(() => {
        const selectAllCheckbox = document.getElementById("selectAllLeads");
        if (selectAllCheckbox) {
            // Prevent sorting when clicking the checkbox in header
            selectAllCheckbox.addEventListener("click", function (e) {
                e.stopPropagation(); // Prevent triggering sorting
            });

            // Handle select/unselect all checkboxes
            selectAllCheckbox.addEventListener("change", function () {
                const isChecked = this.checked;
                const checkboxes = document.querySelectorAll(".lead-checkbox");
                checkboxes.forEach(cb => cb.checked = isChecked);
            });
        }
        
        // selection of new leaads
        const selectAllNewCheckbox = document.getElementById("selectAllNewLeads");
        if (selectAllNewCheckbox) {
            // Prevent sorting when clicking the checkbox in header
            selectAllNewCheckbox.addEventListener("click", function (e) {
                e.stopPropagation(); // Prevent triggering sorting
            });

            // Handle select/unselect all checkboxes
            selectAllNewCheckbox.addEventListener("change", function () {
                const isNewChecked = this.checked;
                const newcheckboxes = document.querySelectorAll(".newlead-checkbox");
                newcheckboxes.forEach(cb => cb.checked = isNewChecked);
            });
        }
    }, 500); // Slight delay to ensure Grid.js renders DOM
    
});

// Triggered when user clicks "Delete Leads" button
document.getElementById("openDeleteCanvas").addEventListener("click", function () {
    enabledeleteleadCheckboxSelection = true;
    filters = { selecteddelStatus: "deleteleads" };

    // Store the selectedStatus in session (using AJAX)
    fetch('store-session.php', {
        method: 'POST',
        body: JSON.stringify({ selecteddelStatus: "deleteleads" }),
        headers: { 'Content-Type': 'application/json' }
    })
    .then(response => response.json())
    .then(data => {
        console.log("Selected status stored in session:", data);
    })
    .catch(error => {
        console.error("Error storing selectedStatus in session:", error);
    });

    // Show the confirm button container
    document.getElementById("confirmDeleteContainer").style.display = "block";

    // Reinitialize both tables with checkbox column
    initializeAllTable();
    initializeDeadLeadsTable();

    // After short delay to let Grid.js finish rendering
    setTimeout(() => {
        
        const selectAllCheckbox = document.getElementById("selectAllLeadsDelete");
        if (selectAllCheckbox) {
            // Prevent sorting when clicking the checkbox in header
            selectAllCheckbox.addEventListener("click", function (e) {
                e.stopPropagation(); // Prevent triggering sorting
            });

            // Handle select/unselect all checkboxes
            selectAllCheckbox.addEventListener("change", function () {
                const isChecked = this.checked;
                const checkboxes = document.querySelectorAll(".lead-checkbox");
                checkboxes.forEach(cb => cb.checked = isChecked);
            });
        }
        
        const selectAllDelCheckbox = document.getElementById("selectAllDeleteLeads");
        if (selectAllDelCheckbox) {
            // Prevent sorting when clicking the checkbox in header
            selectAllDelCheckbox.addEventListener("click", function (e) {
                e.stopPropagation(); // Prevent triggering sorting
            });

            // Handle select/unselect all checkboxes
            selectAllDelCheckbox.addEventListener("change", function () {
                const isChecked = this.checked;
                const checkboxes = document.querySelectorAll(".delete-lead-checkbox");
                checkboxes.forEach(cb => cb.checked = isChecked);
            });
        }
        
    }, 500); // Slight delay to ensure Grid.js renders DOM
    
});



function setupSelectAllCheckboxes() {
    // All Leads checkbox
    const selectAllCheckbox = document.getElementById("selectAllLeads");
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener("click", e => e.stopPropagation());
        selectAllCheckbox.addEventListener("change", function () {
            const isChecked = this.checked;
            document.querySelectorAll(".lead-checkbox").forEach(cb => cb.checked = isChecked);
        });
    }

    // New Leads checkbox
    const selectAllNewCheckbox = document.getElementById("selectAllNewLeads");
    if (selectAllNewCheckbox) {
        selectAllNewCheckbox.addEventListener("click", e => e.stopPropagation());
        selectAllNewCheckbox.addEventListener("change", function () {
            const isNewChecked = this.checked;
            document.querySelectorAll(".newlead-checkbox").forEach(cb => cb.checked = isNewChecked);
        });
    }
}

document.getElementById("confirmReassignBtn").addEventListener("click", function () {
    const selectedLeads = Array.from(document.querySelectorAll(".lead-checkbox:checked"))
        .map(cb => cb.value);
        
    const newselectedLeads = Array.from(document.querySelectorAll(".newlead-checkbox:checked"))
        .map(cb => cb.value);

    if (selectedLeads.length === 0 && newselectedLeads.length === 0) {
        alert("Please select at least one lead to reassign.");
        return;
    }
    
    // if (newselectedLeads.length === 0) {
    //     alert("Please select at least one lead to reassign.");
    //     return;
    // }

    // You can pass this data to the canvas or pre-fill a hidden input
    console.log("Selected leads for reassignment:", selectedLeads);
    
     console.log("Selected leads for reassignment:", newselectedLeads);

    // Open the reassign canvas manually
    const offcanvas = new bootstrap.Offcanvas(document.getElementById('rightOffcanvas1'));
    offcanvas.show();

    // Optionally pass the selected leads to an input inside canvas
    document.getElementById("selectedLeadIdsInput").value = selectedLeads.join(",");
    document.getElementById("newselectedLeadIdsInput").value = newselectedLeads.join(",");
});

document.getElementById("confirmDeleteBtn").addEventListener("click", function () {
    
    const selectedLeads = Array.from(document.querySelectorAll(".lead-checkbox:checked"))
        .map(cb => cb.value);
    
    const selectedDeleteLeads = Array.from(document.querySelectorAll(".delete-lead-checkbox:checked"))
        .map(cb => cb.value);

    if (selectedLeads.length === 0 && selectedDeleteLeads.length === 0) {
        alert("Please select at least one lead to delete.");
        return;
    }

    // Confirm with user
    if (!confirm("Are you sure you want to delete the selected leads?")) {
        return; // User cancelled
    }

    // Send to API (use Fetch)
    fetch('delete-leads-api.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ leadIds: selectedDeleteLeads, deleteLeadIds: selectedLeads })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert("Selected leads deleted successfully!");
            // Reload the table or refresh
            initializeDeadLeadsTable();
        } else {
            alert("Error deleting leads: " + data.message);
        }
    })
    .catch(error => {
        console.error("Error:", error);
        alert("An unexpected error occurred.");
    });
});





//let enableCheckboxSelection = false;

// Keep your existing table initialization functions but rename them according to the above structure
function initializeAllTable() {
    if (document.getElementById("table-gridjs")) {
        let columns = [];
        
        // Conditionally add checkbox column
        if (enableCheckboxSelection) {
            columns.unshift({
                name: gridjs.html('<input type="checkbox" id="selectAllLeads" /> All'),
                width: '40px',
                sort: false,
                formatter: (_, row) => {
                    const leadId = row.cells[row.cells.length - 1]?.data; // Assuming ID is at the end
                    return gridjs.html(`<input type="checkbox" class="lead-checkbox" value="${leadId}" />`);
                }
            });
        }
        
        // Conditionally add checkbox column
        if (enabledeleteleadCheckboxSelection) {
            columns.unshift({
                name: gridjs.html('<input type="checkbox" id="selectAllLeadsDelete" /> All'),
                width: '40px',
                sort: false,
                formatter: (_, row) => {
                    const leadId = row.cells[row.cells.length - 1]?.data; // Assuming ID is at the end
                    return gridjs.html(`<input type="checkbox" class="lead-checkbox" value="${leadId}" />`);
                }
            });
        }
        
        // Add the rest of your columns
        columns.push(
            {
                name: "S.No.",
                formatter: function(e) {
                    return gridjs.html('<span class="fw-semibold">' + e + "</span>");
                }
            }, 
            {
                name: "Name",
                formatter: function (e, row) {
                    let rawData = row._;
                    let leadId = row.cells[11]?.data;
                    let encodedLeadId = leadId ? btoa(leadId) : '#';
                    let leadStatus = row.cells[4].data;
                    
                    // Initialize variables for leadName and leadCount
                    let leadName = '';
                    let leadCount = 0;
            
                    // Check if Name is in column 0 (empty name), then extract from column 2, otherwise from column 1
                    if (row.cells[0].data === '') {
                        let nameParts = row.cells[2]?.data.split('-');
                        leadName = nameParts[0].trim();
                        leadCount = parseInt(nameParts[2] || '0', 10);  // Default to 0 if parsing fails
                    } else {
                        let nameParts = row.cells[1]?.data.split('-');
                        leadName = nameParts[0].trim();
                        leadCount = parseInt(nameParts[1] || '0', 10);  // Default to 0 if parsing fails
                    }
            
                    // Define the duplicate information
                    let duplicateInfo = '';
                    if (leadCount > 0) {
                        duplicateInfo = `
                            <div style="color: #ff4d4f; font-size: 13px; margin-bottom: 4px;">
                                &#x2190; ${leadCount} Duplicates
                            </div>
                        `;
                    }
            
                    // Define the name HTML, making it bold if the status is "New"
                    let nameHtml = (leadStatus === "New") ? `<strong>${leadName}</strong>` : leadName;
            
                    // Construct the full HTML for the cell content
                    let fullHtml = `
                        <div style="display: flex; flex-direction: column; align-items: start;">
                            ${duplicateInfo}
                            <a href="lead-detail.php?id=${encodedLeadId}" target="_blank">${nameHtml}</a>
                        </div>
                    `;
            
                    // Return the formatted HTML
                    return gridjs.html(fullHtml);
                }
            },
            {
                name: "Mobile No.",
                formatter: function(e) {
                   return gridjs.html('<a href="tel:' + e + '">' + e + '</a>');
                }
            },
            {
                name: "Project",
                formatter: function(e) {
                    return gridjs.html('<a href="">' + e + '</a>');
                }
            }, 
            {
                name: "Status",
                formatter: function(e, row) {
                    //let leadName = row.cells[1].data;
                    let leadId = row.cells[11].data;
                    
                    // Initialize variables for leadName and leadCount
                    let leadName = '';
                    //let leadCount = 0;
            
                    // Check if Name is in column 0 (empty name), then extract from column 2, otherwise from column 1
                    if (row.cells[0].data === '') {
                        let nameParts = row.cells[2]?.data.split('-');
                        leadName = nameParts[0].trim();
                        //leadCount = parseInt(nameParts[2] || '0', 10);  // Default to 0 if parsing fails
                    } else {
                        let nameParts = row.cells[1]?.data.split('-');
                        leadName = nameParts[0].trim();
                        //leadCount = parseInt(nameParts[1] || '0', 10);  // Default to 0 if parsing fails
                    }
                    
                    // Define status options
                    let statuses = [
                        { key: "Not Connected", id: "notConnectedRightOffcanvas", link: "not-connected-link", dataAttr: "lead-id" },
                        { key: "In Progress", id: "InProgressRightOffcanvas", link: "in-progress-link", dataAttr: "inp-lead-id" },
                        { key: "SV Scheduled", id: "svScheduledRightOffcanvas", link: "sv-scheduled-link", dataAttr: "svs-lead-id" },
                        { key: "SV Completed", id: "svCompletedRightOffcanvas", link: "sv-completed-link", dataAttr: "svc-lead-id" },
                        { key: "EOI Completed", id: "eoiCompletedRightOffcanvas", link: "eoi-completed-link", dataAttr: "eoi-lead-id" },
                        { key: "Booking Completed", id: "bookingCompletedRightOffcanvas", link: "booking-completed-link", dataAttr: "booking-lead-id" },
                        { key: "Dead Lead", id: "deadRightOffcanvas", link: "dead-link", dataAttr: "dead-lead-id" }
                    ];

                    // Find the current status from row data
                    let selectedStatus = statuses.find(status => status.key === e);
                    let buttonText = selectedStatus ? selectedStatus.key : "Select Status";
                    let statusbuttonClass = "btn-primary"; // Default color

                    // Change button color based on intent
                    if (e === "Not Connected" || e === "In Progress") {
                        statusbuttonClass = "btn-primary"; // Red for Hot
                    } else if (e === "SV Scheduled" || e === "SV Completed") {
                        statusbuttonClass = "btn-warning";
                    } else if (e === "EOI Completed" || e === "Booking Completed") {
                        statusbuttonClass = "btn-success";
                    } else if (e === "Dead Lead") {
                        statusbuttonClass = "btn-danger";
                    }

                    // Generate dropdown items
                    let dropdownItems = statuses.map(status => `
                        <a class="dropdown-item ${status.link} ${status.key === e ? 'active' : ''}" 
                           href="javascript: void(0);"
                           data-bs-toggle="offcanvas" 
                           data-bs-target="#${status.id}" 
                           aria-controls="rightOffcanvas"
                           data-lead-name="${leadName}" 
                           data-${status.dataAttr}="${leadId}">
                           ${status.key}
                        </a>
                    `).join("");

                    return gridjs.html(`
                        <div class="dropdown">
                            <button class="btn ${statusbuttonClass} dropdown-toggle" type="button" id="dropdownMenuButton1"
                                    data-bs-toggle="dropdown" aria-expanded="false">
                                ${buttonText}
                            </button>
                            <div class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
                                ${dropdownItems}
                            </div>
                        </div>
                    `);
                }
            },
            {
                name: "Intent",
                width: "120px",
                formatter: function(e) {
                    let buttonClass = "btn-primary"; // Default color
            
                    // Change button color based on intent
                    if (e === "Hot") {
                        buttonClass = "btn-danger"; // Red for Hot
                    } else if (e === "Warm") {
                        buttonClass = "btn-warning"; // Yellow/Orange for Warm
                    } else if (e === "Cold") {
                        buttonClass = "btn-info"; // Blue for Cold
                    } else if (!e || e.trim() === "") {
                        buttonClass = "btn-secondary"; // Gray for Blank/No Intent
                    }
            
                    return gridjs.html(`<button type="button" class="btn ${buttonClass}">${e || "New Lead"}</button>`);
                }
            },
            "Source", 
            "Assigned User", 
            "Created Date", 
            "Assigned Date", 
            "Last Note",
            {
                name: "Actions",
                width: "120px",
                formatter: function(e) {
                    return gridjs.html('<li class="list-inline-item fs-20 dropdown d-none d-md-flex"><a href="javascript: void(0);" class="dropdown-toggle arrow-none text-dark show" data-bs-toggle="dropdown" aria-expanded="true"><i class="ri-more-2-fill"></i></a><div class="dropdown-menu dropdown-menu-end"><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">Re-assigned Lead</a><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">View Recent Activity</a><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">Delete Lead</a></div></li>');
                }
            }
        );

        // Get filter params
        // const filters = {
        //     selectedStatus: "reassignleads"
        // };

        // Initialize the table
        if (window.allLeadsGrid) {
            // Update the existing Grid.js config
            window.allLeadsGrid.updateConfig({
                columns,
                server: {
                    url: '<?php echo $base_url;?>ajax-lead-fetch-data.php',
                    params: filters, // Pass the filters object here
                    then: data => data
                }
            }).forceRender(); // This will force a re-render with the new config
        } else {
            // Create a new instance of Grid.js if not already created
            window.allLeadsGrid = new gridjs.Grid({
                columns,
                pagination: { limit: 100 },
                sort: true,
                search: true,
                server: {
                    url: '<?php echo $base_url;?>ajax-lead-fetch-data.php',
                    params: filters, // Pass the filters object here
                    then: data => data
                }
            });
        
            // Render the new table
            window.allLeadsGrid.render(document.getElementById("table-gridjs"));
        }

    }
}



function initializeNewLeadsTable() {
    if (document.getElementById("table-gridjs-new")) {
        
        let columns = [];
       
    	// Conditionally add checkbox column
    	if (enableNewCheckboxSelection) {
    		columns.unshift({
    			name: gridjs.html('<input type="checkbox" id="selectAllNewLeads" /> All'),
    			width: '40px',
    			sort: false,
    			formatter: (_, row) => {
    				const leadId = row.cells[row.cells.length - 1]?.data; // Assuming ID is at the end
    				return gridjs.html(`<input type="checkbox" class="newlead-checkbox" value="${leadId}" />`);
    			}
    		});
    	}
    	
    		// Add the rest of your columns
        columns.push(
            {
                name: "S.No.",
                formatter: function(e) {
                    return gridjs.html('<span class="fw-semibold">' + e + "</span>")
                }
            },
            {
                name: "Name",
                formatter: function(e, row) {
                    let rawData = row._;
                    let leadId = row.cells[12].data;
                    let encodedLeadId = leadId ? btoa(leadId) : '#';
                    let leadStatus = row.cells[4].data;
                    
                    // Initialize variables for leadName and leadCount
                    let leadName = '';
                    let leadCount = 0;
                
                    // Check if Name is in column 0 (empty name), then extract from column 2, otherwise from column 1
                    if (row.cells[0].data === '') {
                        let nameParts = row.cells[2]?.data.split('-');
                        leadName = nameParts[0].trim();
                        leadCount = parseInt(nameParts[2] || '0', 10);  // Default to 0 if parsing fails
                    } else {
                        let nameParts = row.cells[1]?.data.split('-');
                        leadName = nameParts[0].trim();
                        leadCount = parseInt(nameParts[1] || '0', 10);  // Default to 0 if parsing fails
                    }
                    
                    // Extract name and duplicate count from "Name-Count"
                    // let nameParts = row.cells[1].data.split('-');
                    // let leadName = nameParts[0].trim();
                    // let leadCount = parseInt(nameParts[1] || '0', 10);
            
                    // Just a red left arrow and text
                    let duplicateInfo = '';
                    if (leadCount > 0) {
                        duplicateInfo = `
                            <div style="color: #ff4d4f; font-size: 13px; margin-bottom: 4px;">
                                &#x2190; ${leadCount} Duplicates
                            </div>
                        `;
                    }
            
                    let nameHtml = (leadStatus === "New") ? '<strong>' + leadName + '</strong>' : leadName;
            
                    let fullHtml = `
                        <div style="display: flex; flex-direction: column; align-items: start;">
                            ${duplicateInfo}
                            <a href="lead-detail.php?id=${encodedLeadId}" target="_blank">${nameHtml}</a>
                        </div>
                    `;
            
                    return gridjs.html(fullHtml);
                }
            },
            {
                name: "Mobile No.",
                formatter: function(e) {
                   return gridjs.html('<a href="tel:' + e + '">' + e + '</a>');
                }
            }, 
            {
                name: "Project",
                formatter: function(e) {
                    return gridjs.html('<a href="">' + e + '</a>')
                }
            }, 
            {
                name: "Status",
                formatter: function(e, row) {
                    //let leadName = row.cells[1].data;
                    let leadId = row.cells[12].data;
                    
                     // Initialize variables for leadName and leadCount
                    let leadName = '';
                    //let leadCount = 0;
            
                    // Check if Name is in column 0 (empty name), then extract from column 2, otherwise from column 1
                    if (row.cells[0].data === '') {
                        let nameParts = row.cells[2]?.data.split('-');
                        leadName = nameParts[0].trim();
                        //leadCount = parseInt(nameParts[2] || '0', 10);  // Default to 0 if parsing fails
                    } else {
                        let nameParts = row.cells[1]?.data.split('-');
                        leadName = nameParts[0].trim();
                        //leadCount = parseInt(nameParts[1] || '0', 10);  // Default to 0 if parsing fails
                    }
            
                    // Define status options
                    let statuses = [
                        { key: "Not Connected", id: "notConnectedRightOffcanvas", link: "not-connected-link", dataAttr: "lead-id" },
                        { key: "In Progress", id: "InProgressRightOffcanvas", link: "in-progress-link", dataAttr: "inp-lead-id" },
                        { key: "SV Scheduled", id: "svScheduledRightOffcanvas", link: "sv-scheduled-link", dataAttr: "svs-lead-id" },
                        { key: "SV Completed", id: "svCompletedRightOffcanvas", link: "sv-completed-link", dataAttr: "svc-lead-id" },
                        { key: "EOI Completed", id: "eoiCompletedRightOffcanvas", link: "eoi-completed-link", dataAttr: "eoi-lead-id" },
                        { key: "Booking Completed", id: "bookingCompletedRightOffcanvas", link: "booking-completed-link", dataAttr: "booking-lead-id" },
                        { key: "Dead Lead", id: "deadRightOffcanvas", link: "dead-link", dataAttr: "dead-lead-id" }
                    ];
                    
                    let statusbuttonClass = "btn-primary"; // Default color
            
                    // Change button color based on intent
                    if (e === "Not Connected" || e === "In Progress") {
                        statusbuttonClass = "btn-primary"; // Red for Hot
                    }
                    else if(e === "SV Scheduled" || e === "SV Completed"){
                        statusbuttonClass = "btn-warning";
                    }
                    else if(e === "EOI Completed" || e === "Booking Completed"){
                        statusbuttonClass = "btn-success";
                    }
                    else if(e === "Dead Lead"){
                        statusbuttonClass = "btn-danger";
                    }
            
                    // Find the current status from row data
                    let selectedStatus = statuses.find(status => status.key === e);
                    let buttonText = selectedStatus ? selectedStatus.key : "Select Status";
                    
                    // Determine button color based on status
                    let buttonClass = "btn-secondary"; // Default color
                    if (e === "Not Connected") {
                        buttonClass = "btn-primary"; // Royal blue for Not Connected
                    }
            
                    // Generate dropdown items
                    let dropdownItems = statuses.map(status => `
                        <a class="dropdown-item ${status.link} ${status.key === e ? 'active' : ''}" 
                           href="javascript: void(0);"
                           data-bs-toggle="offcanvas" 
                           data-bs-target="#${status.id}" 
                           aria-controls="rightOffcanvas"
                           data-lead-name="${leadName}" 
                           data-${status.dataAttr}="${leadId}">
                           ${status.key}
                        </a>
                    `).join("");
            
                    return gridjs.html(`
                        <div class="dropdown">
                            <button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenuButton1"
                                    data-bs-toggle="dropdown" aria-expanded="false">
                                ${buttonText}
                            </button>
                            <div class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
                                ${dropdownItems}
                            </div>
                        </div>
                    `);
                }
            },
            {
                name: "Intent",
                width: "120px",
                formatter: function(e) {
                    let buttonClass = "btn-primary"; // Default color
            
                    // Change button color based on intent
                    if (e === "Hot") {
                        buttonClass = "btn-danger"; // Red for Hot
                    } else if (e === "Warm") {
                        buttonClass = "btn-warning"; // Yellow/Orange for Warm
                    } else if (e === "Cold") {
                        buttonClass = "btn-info"; // Blue for Cold
                    } else if (!e || e.trim() === "") {
                        buttonClass = "btn-secondary"; // Gray for Blank/No Intent
                    }
            
                    return gridjs.html(`<button type="button" class="btn ${buttonClass}">${e || "New Lead"}</button>`);
                }
            },
            "Source","Assigned User","Created Date","Assigned Date","City","Last Note",			
            {
                name: "Actions",
                width: "120px",
                formatter: function(e) {
                    return gridjs.html('<li class="list-inline-item fs-20 dropdown d-none d-md-flex"><a href="javascript: void(0);" class="dropdown-toggle arrow-none text-dark show" data-bs-toggle="dropdown" aria-expanded="true"><i class="ri-more-2-fill"></i></a><div class="dropdown-menu dropdown-menu-end"><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">Re-assigned Lead</a><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">View Recent Activity</a><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">Delete Lead</a></div></li>')
                }
            }
            );
            
         // Initialize the table
        if (window.newLeadsGrid) {
            // Update the existing Grid.js config
            window.newLeadsGrid.updateConfig({
                columns,
                server: {
                    url: '<?php echo $base_url;?>new-ajax-lead-fetch-data.php',
                    params: filters, // Pass the filters object here
                    then: data => data
                }
            }).forceRender(); // This will force a re-render with the new config
        } else {
            // Create a new instance of Grid.js if not already created
            window.newLeadsGrid = new gridjs.Grid({
                columns,
                pagination: { limit: 100 },
                sort: true,
                search: true,
                server: {
                    url: '<?php echo $base_url;?>new-ajax-lead-fetch-data.php',
                    params: filters, // Pass the filters object here
                    then: data => data
                }
            });
        
            // Render the new table
            window.newLeadsGrid.render(document.getElementById("table-gridjs-new"));
        }
        
    }
}

function initializefollowupTable() {
    if (document.getElementById("table-gridjs-messages")) {
        window.followupLeadsGrid = new gridjs.Grid({
            columns: [{
                name: "S.No.",
                formatter: function(e) {
                    return gridjs.html('<span class="fw-semibold">' + e + "</span>")
                }
            },
            {
                name: "Name",
                formatter: function(e, row) {
                    let leadId = row.cells[14].data;
                    let encodedLeadId = btoa(leadId);
                    return gridjs.html('<a href="lead-detail.php?id=' + encodedLeadId + '" target="_blank">' + e + '</a>')
                }
            },
            {
                name: "Mobile No.",
                formatter: function(e) {
                   return gridjs.html('<a href="tel:' + e + '">' + e + '</a>');
                }
            }, 
            {
                name: "Project",
                formatter: function(e) {
                    return gridjs.html('<a href="">' + e + '</a>')
                }
            },
            {
            name: "Status",
            formatter: function(e, row) {
                let leadName = row.cells[1].data;
                let leadId = row.cells[14].data;
        
                // Define status options
                let statuses = [
                    { key: "Not Connected", id: "notConnectedRightOffcanvas", link: "not-connected-link", dataAttr: "lead-id" },
                    { key: "In Progress", id: "InProgressRightOffcanvas", link: "in-progress-link", dataAttr: "inp-lead-id" },
                    { key: "SV Scheduled", id: "svScheduledRightOffcanvas", link: "sv-scheduled-link", dataAttr: "svs-lead-id" },
                    { key: "SV Completed", id: "svCompletedRightOffcanvas", link: "sv-completed-link", dataAttr: "svc-lead-id" },
                    { key: "EOI Completed", id: "eoiCompletedRightOffcanvas", link: "eoi-completed-link", dataAttr: "eoi-lead-id" },
                    { key: "Booking Completed", id: "bookingCompletedRightOffcanvas", link: "booking-completed-link", dataAttr: "booking-lead-id" },
                    { key: "Dead Lead", id: "deadRightOffcanvas", link: "dead-link", dataAttr: "dead-lead-id" }
                ];

        
                // Find the current status from row data
                let selectedStatus = statuses.find(status => status.key === e);
                let buttonText = selectedStatus ? selectedStatus.key : "Select Status";
        
                // Generate dropdown items
                let dropdownItems = statuses.map(status => `
                    <a class="dropdown-item ${status.link} ${status.key === e ? 'active' : ''}" 
                       href="javascript: void(0);"
                       data-bs-toggle="offcanvas" 
                       data-bs-target="#${status.id}" 
                       aria-controls="rightOffcanvas"
                       data-lead-name="${leadName}" 
                       data-${status.dataAttr}="${leadId}">
                       ${status.key}
                    </a>
                `).join("");
        
                return gridjs.html(`
                    <div class="dropdown">
                        <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1"
                                data-bs-toggle="dropdown" aria-expanded="false">
                            ${buttonText}
                        </button>
                        <div class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
                            ${dropdownItems}
                        </div>
                    </div>
                `);
            }
        },
            // {
            //     name:"Status",
            //     formatter: function(e, row) {
            //       return gridjs.html('<div class="dropdown"><button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">Select Status </button><div class="dropdown-menu" aria-labelledby="dropdownMenuButton1"><a class="dropdown-item not-connected-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#notConnectedRightOffcanvas" aria-controls="rightOffcanvas" data-lead-name="' + row.cells[1].data + '" data-lead-id="' + row.cells[19].data + '">Not Connected</a><a class="dropdown-item in-progress-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#InProgressRightOffcanvas" aria-controls="rightOffcanvas" data-inp-lead-name="' + row.cells[1].data + '" data-inp-lead-id="' + row.cells[19].data + '">In Progress</a><a class="dropdown-item sv-scheduled-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#svScheduledRightOffcanvas" aria-controls="rightOffcanvas" data-svs-lead-name="' + row.cells[1].data + '" data-svs-lead-id="' + row.cells[19].data + '">SV Scheduled</a><a class="dropdown-item sv-completed-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#svCompletedRightOffcanvas" aria-controls="rightOffcanvas" data-svc-lead-name="' + row.cells[1].data + '" data-svc-lead-id="' + row.cells[19].data + '">SV Completed</a><a class="dropdown-item eoi-completed-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#eoiCompletedRightOffcanvas" aria-controls="rightOffcanvas" data-eoi-lead-name="' + row.cells[1].data + '" data-eoi-lead-id="' + row.cells[19].data + '">EOI Completed</a><a class="dropdown-item booking-completed-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#bookingCompletedRightOffcanvas" aria-controls="rightOffcanvas" data-booking-lead-name="' + row.cells[1].data + '" data-booking-lead-id="' + row.cells[19].data + '">Booking Completed</a><a class="dropdown-item dead-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#deadRightOffcanvas" aria-controls="rightOffcanvas" data-dead-lead-name="' + row.cells[1].data + '" data-dead-lead-id="' + row.cells[19].data + '">Dead Lead</a></div></div>')
            //     }
            // },
// {
//                 name: "Intent",
//                 width: "120px",
//                 formatter: function(e) {
//                     return gridjs.html('<button type="button" class="btn btn-primary">New Lead</button>')
//                 }
//             },
            {
                name: "Intent",
                width: "120px",
                formatter: function(e) {
                    let buttonClass = "btn-primary"; // Default color
            
                    // Change button color based on intent
                    if (e === "Hot") {
                        buttonClass = "btn-danger"; // Red for Hot
                    } else if (e === "Warm") {
                        buttonClass = "btn-warning"; // Yellow/Orange for Warm
                    } else if (e === "Cold") {
                        buttonClass = "btn-info"; // Blue for Cold
                    } else if (!e || e.trim() === "") {
                        buttonClass = "btn-secondary"; // Gray for Blank/No Intent
                    }
            
                    return gridjs.html(`<button type="button" class="btn ${buttonClass}">${e || "New Lead"}</button>`);
                }
            },
            "Source","Assigned User","Created Date","Followup Date","City","Note","Last Note","Reason",			
            {
                name: "Actions",
                width: "120px",
                formatter: function(e) {
                    return gridjs.html('<li class="list-inline-item fs-20 dropdown d-none d-md-flex"><a href="javascript: void(0);" class="dropdown-toggle arrow-none text-dark show" data-bs-toggle="dropdown" aria-expanded="true"><i class="ri-more-2-fill"></i></a><div class="dropdown-menu dropdown-menu-end"><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">Edit Followup</a><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">Re-assigned Lead</a><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">View Recent Activity</a><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">Delete Lead</a></div></li>')
                }
            }],
            pagination: {
                limit: 30
            },
            sort: true,
            search: true,
            server: {
                url: '<?php echo $base_url;?>followup-ajax-lead-fetch-data.php',  // The PHP script that fetches data
                then: data => data,     // Process the fetched data
                // You can handle any other server-side processing here if necessary
                // data: function(params) {
                //     // Get selected projects from the checkboxes
                //     const selectedProjects = Array.from(document.querySelectorAll('.project-checkbox:checked'))
                //         .map(checkbox => checkbox.value);
                    
                //     // Add the projects parameter to the request
                //     if (selectedProjects.length > 0) {
                //         params.projects = selectedProjects;
                //     }
                    
                //     return params;
                // }
            }
        });
        
        window.followupLeadsGrid.render(document.getElementById("table-gridjs-messages"));
    }
}

function initializeSVScheduledTable() {
    console.log('Kamal');
    // Your existing SV Scheduled table initialization code
    if (document.getElementById("table-gridjs-new-svscheduled")) {
        window.svScheduledLeadsGrid = new gridjs.Grid({
            columns: [{
                name: "S.No.",
                formatter: function(e) {
                    return gridjs.html('<span class="fw-semibold">' + e + "</span>")
                }
            },
            {
                name: "Name",
                formatter: function(e, row) {
                    let leadId = row.cells[17].data;
                    let encodedLeadId = btoa(leadId);
                    return gridjs.html('<a href="lead-detail.php?id=' + encodedLeadId + '" target="_blank">' + e + '</a>')
                }
            },
            {
                name: "Mobile No.",
                formatter: function(e) {
                   return gridjs.html('<a href="tel:' + e + '">' + e + '</a>');
                }
            },
            {
                name: "Project",
                formatter: function(e) {
                    return gridjs.html('<a href="">' + e + '</a>')
                }
            }, 
            {
            name: "Status",
            formatter: function(e, row) {
                let leadName = row.cells[1].data;
                let leadId = row.cells[17].data;
        
                // Define status options
                let statuses = [
                    { key: "Not Connected", id: "notConnectedRightOffcanvas", link: "not-connected-link", dataAttr: "lead-id" },
                    { key: "In Progress", id: "InProgressRightOffcanvas", link: "in-progress-link", dataAttr: "inp-lead-id" },
                    { key: "SV Scheduled", id: "svScheduledRightOffcanvas", link: "sv-scheduled-link", dataAttr: "svs-lead-id" },
                    { key: "SV Completed", id: "svCompletedRightOffcanvas", link: "sv-completed-link", dataAttr: "svc-lead-id" },
                    { key: "EOI Completed", id: "eoiCompletedRightOffcanvas", link: "eoi-completed-link", dataAttr: "eoi-lead-id" },
                    { key: "Booking Completed", id: "bookingCompletedRightOffcanvas", link: "booking-completed-link", dataAttr: "booking-lead-id" },
                    { key: "Dead Lead", id: "deadRightOffcanvas", link: "dead-link", dataAttr: "dead-lead-id" }
                ];

        
                // Find the current status from row data
                let selectedStatus = statuses.find(status => status.key === e);
                let buttonText = selectedStatus ? selectedStatus.key : "Select Status";
                
                let statusbuttonClass = "btn-primary"; // Default color
            
                    // Change button color based on intent
                    if (e === "SV Scheduled") {
                        statusbuttonClass = "btn-warning"; // Red for Hot
                    } 
                
                // Generate dropdown items
                let dropdownItems = statuses.map(status => `
                    <a class="dropdown-item ${status.link} ${status.key === e ? 'active' : ''}" 
                       href="javascript: void(0);"
                       data-bs-toggle="offcanvas" 
                       data-bs-target="#${status.id}" 
                       aria-controls="rightOffcanvas"
                       data-lead-name="${leadName}" 
                       data-${status.dataAttr}="${leadId}">
                       ${status.key}
                    </a>
                `).join("");
        
                return gridjs.html(`
                    <div class="dropdown">
                        <button class="btn  ${statusbuttonClass} dropdown-toggle" type="button" id="dropdownMenuButton1"
                                data-bs-toggle="dropdown" aria-expanded="false">
                            ${buttonText}
                        </button>
                        <div class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
                            ${dropdownItems}
                        </div>
                    </div>
                `);
            }
        },
            // {
            //     name:"Status",
            //     formatter: function(e, row) {
            //       return gridjs.html('<div class="dropdown"><button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">Select Status </button><div class="dropdown-menu" aria-labelledby="dropdownMenuButton1"><a class="dropdown-item not-connected-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#notConnectedRightOffcanvas" aria-controls="rightOffcanvas" data-lead-name="' + row.cells[1].data + '" data-lead-id="' + row.cells[22].data + '">Not Connected</a><a class="dropdown-item in-progress-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#InProgressRightOffcanvas" aria-controls="rightOffcanvas" data-inp-lead-name="' + row.cells[1].data + '" data-inp-lead-id="' + row.cells[22].data + '">In Progress</a><a class="dropdown-item sv-scheduled-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#svScheduledRightOffcanvas" aria-controls="rightOffcanvas" data-svs-lead-name="' + row.cells[1].data + '" data-svs-lead-id="' + row.cells[22].data + '">SV Scheduled</a><a class="dropdown-item sv-completed-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#svCompletedRightOffcanvas" aria-controls="rightOffcanvas" data-svc-lead-name="' + row.cells[1].data + '" data-svc-lead-id="' + row.cells[22].data + '">SV Completed</a><a class="dropdown-item eoi-completed-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#eoiCompletedRightOffcanvas" aria-controls="rightOffcanvas" data-eoi-lead-name="' + row.cells[1].data + '" data-eoi-lead-id="' + row.cells[22].data + '">EOI Completed</a><a class="dropdown-item booking-completed-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#bookingCompletedRightOffcanvas" aria-controls="rightOffcanvas" data-booking-lead-name="' + row.cells[1].data + '" data-booking-lead-id="' + row.cells[22].data + '">Booking Completed</a><a class="dropdown-item dead-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#deadRightOffcanvas" aria-controls="rightOffcanvas" data-dead-lead-name="' + row.cells[1].data + '" data-dead-lead-id="' + row.cells[22].data + '">Dead Lead</a></div></div>')
            //     }
            // },
// {
//                 name: "Intent",
//                 width: "120px",
//                 formatter: function(e) {
//                     return gridjs.html('<button type="button" class="btn btn-primary">New Lead</button>')
//                 }
//             },
            {
                name: "Intent",
                width: "120px",
                formatter: function(e) {
                    let buttonClass = "btn-primary"; // Default color
            
                    // Change button color based on intent
                    if (e === "Hot") {
                        buttonClass = "btn-danger"; // Red for Hot
                    } else if (e === "Warm") {
                        buttonClass = "btn-warning"; // Yellow/Orange for Warm
                    } else if (e === "Cold") {
                        buttonClass = "btn-info"; // Blue for Cold
                    } else if (!e || e.trim() === "") {
                        buttonClass = "btn-secondary"; // Gray for Blank/No Intent
                    }
            
                    return gridjs.html(`<button type="button" class="btn ${buttonClass}">${e || "New Lead"}</button>`);
                }
            },
            "Source","Assigned User","Created Date","Site Visit Date","Followup Date","City","Note","Type of Site Visit","SV Project","SV Duration","Last Note",			
            {
                name: "Actions",
                width: "120px",
                formatter: function(e) {
                    return gridjs.html('<li class="list-inline-item fs-20 dropdown d-none d-md-flex"><a href="javascript: void(0);" class="dropdown-toggle arrow-none text-dark show" data-bs-toggle="dropdown" aria-expanded="true"><i class="ri-more-2-fill"></i></a><div class="dropdown-menu dropdown-menu-end"><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">Edit Site Visit</a><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">Re-assigned Lead</a><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">View Recent Activity</a><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">Delete Lead</a></div></li>')
                }
            }],
            pagination: {
                limit: 30
            },
            sort: true,
            search: true,
            server: {
                url: '<?php echo $base_url;?>svscheduled-ajax-lead-fetch-data.php',  // The PHP script that fetches data
                then: data => data,     // Process the fetched data
                // You can handle any other server-side processing here if necessary
                // data: function(params) {
                //     // Get selected projects from the checkboxes
                //     const selectedProjects = Array.from(document.querySelectorAll('.project-checkbox:checked'))
                //         .map(checkbox => checkbox.value);
                    
                //     // Add the projects parameter to the request
                //     if (selectedProjects.length > 0) {
                //         params.projects = selectedProjects;
                //     }
                    
                //     return params;
                // }
            }
        });
        //}).render(document.getElementById("table-gridjs-new-svscheduled"));
        window.svScheduledLeadsGrid.render(document.getElementById("table-gridjs-new-svscheduled"));
    }
}

function initializeSVCompletedTable() {
    // Your existing SV Completed table initialization code
    if (document.getElementById("table-gridjs-new-svcompleted")) {
        window.svCompletedLeadsGrid = new gridjs.Grid({
            columns: [{
                name: "S.No.",
                formatter: function(e) {
                    return gridjs.html('<span class="fw-semibold">' + e + "</span>")
                }
            }, 
            {
                name: "Name",
                formatter: function(e, row) {
                    let leadId = row.cells[17].data;
                    let encodedLeadId = btoa(leadId);
                    return gridjs.html('<a href="lead-detail.php?id=' + encodedLeadId + '" target="_blank">' + e + '</a>')
                }
            },
            {
                name: "Mobile No.",
                formatter: function(e) {
                   return gridjs.html('<a href="tel:' + e + '">' + e + '</a>');
                }
            }, 
            {
                name: "Project",
                formatter: function(e) {
                    return gridjs.html('<a href="">' + e + '</a>')
                }
            },
            {
            name: "Status",
            formatter: function(e, row) {
                let leadName = row.cells[1].data;
                let leadId = row.cells[17].data;
        
                // Define status options
                let statuses = [
                    { key: "Not Connected", id: "notConnectedRightOffcanvas", link: "not-connected-link", dataAttr: "lead-id" },
                    { key: "In Progress", id: "InProgressRightOffcanvas", link: "in-progress-link", dataAttr: "inp-lead-id" },
                    { key: "SV Scheduled", id: "svScheduledRightOffcanvas", link: "sv-scheduled-link", dataAttr: "svs-lead-id" },
                    { key: "SV Completed", id: "svCompletedRightOffcanvas", link: "sv-completed-link", dataAttr: "svc-lead-id" },
                    { key: "EOI Completed", id: "eoiCompletedRightOffcanvas", link: "eoi-completed-link", dataAttr: "eoi-lead-id" },
                    { key: "Booking Completed", id: "bookingCompletedRightOffcanvas", link: "booking-completed-link", dataAttr: "booking-lead-id" },
                    { key: "Dead Lead", id: "deadRightOffcanvas", link: "dead-link", dataAttr: "dead-lead-id" }
                ];

        
                // Find the current status from row data
                let selectedStatus = statuses.find(status => status.key === e);
                let buttonText = selectedStatus ? selectedStatus.key : "Select Status";
                
                let statusbuttonClass = "btn-primary"; // Default color
            
                // Change button color based on intent
                if (e === "SV Completed") {
                    statusbuttonClass = "btn-warning"; // Red for Hot
                }
                // Generate dropdown items
                let dropdownItems = statuses.map(status => `
                    <a class="dropdown-item ${status.link} ${status.key === e ? 'active' : ''}" 
                       href="javascript: void(0);"
                       data-bs-toggle="offcanvas" 
                       data-bs-target="#${status.id}" 
                       aria-controls="rightOffcanvas"
                       data-lead-name="${leadName}" 
                       data-${status.dataAttr}="${leadId}">
                       ${status.key}
                    </a>
                `).join("");
        
                return gridjs.html(`
                    <div class="dropdown">
                        <button class="btn ${statusbuttonClass} dropdown-toggle" type="button" id="dropdownMenuButton1"
                                data-bs-toggle="dropdown" aria-expanded="false">
                            ${buttonText}
                        </button>
                        <div class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
                            ${dropdownItems}
                        </div>
                    </div>
                `);
            }
        },
            
            // {
            //     name:"Status",
            //     formatter: function(e, row) {
            //         return gridjs.html('<div class="dropdown"><button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">Select Status </button><div class="dropdown-menu" aria-labelledby="dropdownMenuButton1"><a class="dropdown-item not-connected-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#notConnectedRightOffcanvas" aria-controls="rightOffcanvas" data-lead-name="' + row.cells[1].data + '" data-lead-id="' + row.cells[22].data + '">Not Connected</a><a class="dropdown-item in-progress-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#InProgressRightOffcanvas" aria-controls="rightOffcanvas" data-inp-lead-name="' + row.cells[1].data + '" data-inp-lead-id="' + row.cells[22].data + '">In Progress</a><a class="dropdown-item sv-scheduled-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#svScheduledRightOffcanvas" aria-controls="rightOffcanvas" data-svs-lead-name="' + row.cells[1].data + '" data-svs-lead-id="' + row.cells[22].data + '">SV Scheduled</a><a class="dropdown-item sv-completed-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#svCompletedRightOffcanvas" aria-controls="rightOffcanvas" data-svc-lead-name="' + row.cells[1].data + '" data-svc-lead-id="' + row.cells[22].data + '">SV Completed</a><a class="dropdown-item eoi-completed-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#eoiCompletedRightOffcanvas" aria-controls="rightOffcanvas" data-eoi-lead-name="' + row.cells[1].data + '" data-eoi-lead-id="' + row.cells[22].data + '">EOI Completed</a><a class="dropdown-item booking-completed-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#bookingCompletedRightOffcanvas" aria-controls="rightOffcanvas" data-booking-lead-name="' + row.cells[1].data + '" data-booking-lead-id="' + row.cells[22].data + '">Booking Completed</a><a class="dropdown-item dead-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#deadRightOffcanvas" aria-controls="rightOffcanvas" data-dead-lead-name="' + row.cells[1].data + '" data-dead-lead-id="' + row.cells[22].data + '">Dead Lead</a></div></div>')
            //     }
            // },
// {
//                 name: "Intent",
//                 width: "120px",
//                 formatter: function(e) {
//                     return gridjs.html('<button type="button" class="btn btn-primary">New Lead</button>')
//                 }
//             },
            {
                name: "Intent",
                width: "120px",
                formatter: function(e) {
                    let buttonClass = "btn-primary"; // Default color
            
                    // Change button color based on intent
                    if (e === "Hot") {
                        buttonClass = "btn-danger"; // Red for Hot
                    } else if (e === "Warm") {
                        buttonClass = "btn-warning"; // Yellow/Orange for Warm
                    } else if (e === "Cold") {
                        buttonClass = "btn-info"; // Blue for Cold
                    } else if (!e || e.trim() === "") {
                        buttonClass = "btn-secondary"; // Gray for Blank/No Intent
                    }
            
                    return gridjs.html(`<button type="button" class="btn ${buttonClass}">${e || "New Lead"}</button>`);
                }
            },
            "Source","Assigned User","Created Date","Site Visit Date","Followup Date","City","Note","Type of Site Visit","SV Project","SV Duration","Last Note",			
            {
                name: "Actions",
                width: "120px",
                formatter: function(e) {
                    return gridjs.html('<li class="list-inline-item fs-20 dropdown d-none d-md-flex"><a href="javascript: void(0);" class="dropdown-toggle arrow-none text-dark show" data-bs-toggle="dropdown" aria-expanded="true"><i class="ri-more-2-fill"></i></a><div class="dropdown-menu dropdown-menu-end"><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">Edit Site Visit</a><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">Re-assigned Lead</a><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">View Recent Activity</a><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">Delete Lead</a></div></li>')
                }
            }],
            pagination: {
                limit: 30
            },
            sort: true,
            search: true,
            server: {
                url: '<?php echo $base_url;?>svcompleted-ajax-lead-fetch-data.php',  // The PHP script that fetches data
                then: data => data,     // Process the fetched data
                // You can handle any other server-side processing here if necessary
                // data: function(params) {
                //     // Get selected projects from the checkboxes
                //     const selectedProjects = Array.from(document.querySelectorAll('.project-checkbox:checked'))
                //         .map(checkbox => checkbox.value);
                    
                //     // Add the projects parameter to the request
                //     if (selectedProjects.length > 0) {
                //         params.projects = selectedProjects;
                //     }
                    
                //     return params;
                // }
            }
        });
        //}).render(document.getElementById("table-gridjs-new-svcompleted"));
        window.svCompletedLeadsGrid.render(document.getElementById("table-gridjs-new-svcompleted"));
    }
}

function initializeBookingEOITable() {
    // Your existing Booking/EOI table initialization code
    if (document.getElementById("table-gridjs-new-bookingeois")) {
        window.bookingLeadsGrid = new gridjs.Grid({
            columns: [{
                name: "S.No.",
                formatter: function(e) {
                    return gridjs.html('<span class="fw-semibold">' + e + "</span>")
                }
            },
            {
                name: "Name",
                formatter: function(e, row) {
                    let leadId = row.cells[13].data;
                    let encodedLeadId = btoa(leadId);
                    return gridjs.html('<a href="lead-detail.php?id=' + encodedLeadId + '" target="_blank">' + e + '</a>') 
                }
            },
            {
                name: "Mobile No.",
                formatter: function(e) {
                   return gridjs.html('<a href="tel:' + e + '">' + e + '</a>');
                }
            },
            {
                name: "Project",
                formatter: function(e) {
                    return gridjs.html('<a href="">' + e + '</a>')
                }
            }, 
            {
            name: "Status",
            formatter: function(e, row) {
                let leadName = row.cells[1].data;
                let leadId = row.cells[13].data;
        
                // Define status options
                let statuses = [
                    { key: "Not Connected", id: "notConnectedRightOffcanvas", link: "not-connected-link", dataAttr: "lead-id" },
                    { key: "In Progress", id: "InProgressRightOffcanvas", link: "in-progress-link", dataAttr: "inp-lead-id" },
                    { key: "SV Scheduled", id: "svScheduledRightOffcanvas", link: "sv-scheduled-link", dataAttr: "svs-lead-id" },
                    { key: "SV Completed", id: "svCompletedRightOffcanvas", link: "sv-completed-link", dataAttr: "svc-lead-id" },
                    { key: "EOI Completed", id: "eoiCompletedRightOffcanvas", link: "eoi-completed-link", dataAttr: "eoi-lead-id" },
                    { key: "Booking Completed", id: "bookingCompletedRightOffcanvas", link: "booking-completed-link", dataAttr: "booking-lead-id" },
                    { key: "Dead Lead", id: "deadRightOffcanvas", link: "dead-link", dataAttr: "dead-lead-id" }
                ];
                
                let statusbuttonClass = "btn-primary"; // Default color
            
                // Change button color based on intent
                if (e === "Booking Completed" || e === "EOI Completed") {
                    statusbuttonClass = "btn-success"; // Red for Hot
                }
        
                // Find the current status from row data
                let selectedStatus = statuses.find(status => status.key === e);
                let buttonText = selectedStatus ? selectedStatus.key : "Select Status";
        
                // Generate dropdown items
                let dropdownItems = statuses.map(status => `
                    <a class="dropdown-item ${status.link} ${status.key === e ? 'active' : ''}" 
                       href="javascript: void(0);"
                       data-bs-toggle="offcanvas" 
                       data-bs-target="#${status.id}" 
                       aria-controls="rightOffcanvas"
                       data-lead-name="${leadName}" 
                       data-${status.dataAttr}="${leadId}">
                       ${status.key}
                    </a>
                `).join("");
        
                return gridjs.html(`
                    <div class="dropdown">
                        <button class="btn ${statusbuttonClass} dropdown-toggle" type="button" id="dropdownMenuButton1"
                                data-bs-toggle="dropdown" aria-expanded="false">
                            ${buttonText}
                        </button>
                        <div class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
                            ${dropdownItems}
                        </div>
                    </div>
                `);
            }
        },
        // {
        //         name: "Intent",
        //         width: "120px",
        //         formatter: function(e) {
        //             return gridjs.html('<button type="button" class="btn btn-primary">New Lead</button>')
        //         }
        //     },
            {
                name: "Intent",
                width: "120px",
                formatter: function(e) {
                    let buttonClass = "btn-primary"; // Default color
            
                    // Change button color based on intent
                    if (e === "Hot") {
                        buttonClass = "btn-danger"; // Red for Hot
                    } else if (e === "Warm") {
                        buttonClass = "btn-warning"; // Yellow/Orange for Warm
                    } else if (e === "Cold") {
                        buttonClass = "btn-info"; // Blue for Cold
                    } else if (!e || e.trim() === "") {
                        buttonClass = "btn-secondary"; // Gray for Blank/No Intent
                    }
            
                    return gridjs.html(`<button type="button" class="btn ${buttonClass}">${e || "New Lead"}</button>`);
                }
            },
            "Source","Assigned User","Booking EOI Date","Followup Date","City","Note","Last Note",			
            {
                name: "Actions",
                width: "120px",
                formatter: function(e) {
                    return gridjs.html('<li class="list-inline-item fs-20 dropdown d-none d-md-flex"><a href="javascript: void(0);" class="dropdown-toggle arrow-none text-dark show" data-bs-toggle="dropdown" aria-expanded="true"><i class="ri-more-2-fill"></i></a><div class="dropdown-menu dropdown-menu-end"><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">Edit Booking</a><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">Re-assigned Lead</a><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">View Recent Activity</a><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">Delete Lead</a></div></li>')
                }
            }],
            pagination: {
                limit: 30
            },
            sort: true,
            search: true,
            server: {
                url: '<?php echo $base_url;?>bookingeoi-ajax-lead-fetch-data.php',  // The PHP script that fetches data
                then: data => data,     // Process the fetched data
                // You can handle any other server-side processing here if necessary
                // data: function(params) {
                //     // Get selected projects from the checkboxes
                //     const selectedProjects = Array.from(document.querySelectorAll('.project-checkbox:checked'))
                //         .map(checkbox => checkbox.value);
                    
                //     // Add the projects parameter to the request
                //     if (selectedProjects.length > 0) {
                //         params.projects = selectedProjects;
                //     }
                    
                //     return params;
                // }
            }
        });
        window.bookingLeadsGrid.render(document.getElementById("table-gridjs-new-bookingeois"));
    }
}


function initializeDeadLeadsTable() {
    // Your existing Dead leads table initialization code
    if (document.getElementById("table-gridjs-new-dead")) {
        let columns = [];
        
        // Conditionally add checkbox column
        if (enabledeleteleadCheckboxSelection) {
            columns.unshift({
                name: gridjs.html('<input type="checkbox" id="selectAllDeleteLeads" /> All'),
                width: '40px',
                sort: false,
                formatter: (_, row) => {
                    const leadId = row.cells[row.cells.length - 1]?.data; // Assuming ID is at the end
                    return gridjs.html(`<input type="checkbox" class="delete-lead-checkbox" value="${leadId}" />`);
                }
            });
        }
        
        // Add the rest of your columns
        columns.push(
            {
                name: "S.No.",
                formatter: function(e) {
                    return gridjs.html('<span class="fw-semibold">' + e + "</span>")
                }
            },
            {
                name: "Name",
                formatter: function(e, row) {
                    let leadId = row.cells[12].data;
                    let encodedLeadId = btoa(leadId);
                    return gridjs.html('<a href="lead-detail.php?id=' + encodedLeadId + '" target="_blank">' + e + '</a>')
                }
            },
            {
                name: "Mobile No.",
                formatter: function(e) {
                   return gridjs.html('<a href="tel:' + e + '">' + e + '</a>');
                }
            }, 
            {
                name: "Project",
                formatter: function(e) {
                    return gridjs.html('<a href="">' + e + '</a>')
                }
            },
            {
            name: "Status",
            formatter: function(e, row) {
                let leadName = row.cells[1].data;
                let leadId = row.cells[12].data;
        
                // Define status options
                let statuses = [
                    { key: "Not Connected", id: "notConnectedRightOffcanvas", link: "not-connected-link", dataAttr: "lead-id" },
                    { key: "In Progress", id: "InProgressRightOffcanvas", link: "in-progress-link", dataAttr: "inp-lead-id" },
                    { key: "SV Scheduled", id: "svScheduledRightOffcanvas", link: "sv-scheduled-link", dataAttr: "svs-lead-id" },
                    { key: "SV Completed", id: "svCompletedRightOffcanvas", link: "sv-completed-link", dataAttr: "svc-lead-id" },
                    { key: "EOI Completed", id: "eoiCompletedRightOffcanvas", link: "eoi-completed-link", dataAttr: "eoi-lead-id" },
                    { key: "Booking Completed", id: "bookingCompletedRightOffcanvas", link: "booking-completed-link", dataAttr: "booking-lead-id" },
                    { key: "Dead Lead", id: "deadRightOffcanvas", link: "dead-link", dataAttr: "dead-lead-id" }
                ];

                let statusbuttonClass = "btn-primary"; // Default color
            
                // Change button color based on intent
                if (e === "Dead Lead") {
                    statusbuttonClass = "btn-danger"; // Red for Hot
                }
                // Find the current status from row data
                let selectedStatus = statuses.find(status => status.key === e);
                let buttonText = selectedStatus ? selectedStatus.key : "Select Status";
        
                // Generate dropdown items
                let dropdownItems = statuses.map(status => `
                    <a class="dropdown-item ${status.link} ${status.key === e ? 'active' : ''}" 
                       href="javascript: void(0);"
                       data-bs-toggle="offcanvas" 
                       data-bs-target="#${status.id}" 
                       aria-controls="rightOffcanvas"
                       data-lead-name="${leadName}" 
                       data-${status.dataAttr}="${leadId}">
                       ${status.key}
                    </a>
                `).join("");
        
                return gridjs.html(`
                    <div class="dropdown">
                        <button class="btn ${statusbuttonClass} dropdown-toggle" type="button" id="dropdownMenuButton1"
                                data-bs-toggle="dropdown" aria-expanded="false">
                            ${buttonText}
                        </button>
                        <div class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
                            ${dropdownItems}
                        </div>
                    </div>
                `);
            }
        },
            // {
            //     name:"Status",
            //     formatter: function(e, row) {
            //       return gridjs.html('<div class="dropdown"><button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">Select Status </button><div class="dropdown-menu" aria-labelledby="dropdownMenuButton1"><a class="dropdown-item not-connected-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#notConnectedRightOffcanvas" aria-controls="rightOffcanvas" data-lead-name="' + row.cells[1].data + '" data-lead-id="' + row.cells[17].data + '">Not Connected</a><a class="dropdown-item in-progress-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#InProgressRightOffcanvas" aria-controls="rightOffcanvas" data-inp-lead-name="' + row.cells[1].data + '" data-inp-lead-id="' + row.cells[17].data + '">In Progress</a><a class="dropdown-item sv-scheduled-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#svScheduledRightOffcanvas" aria-controls="rightOffcanvas" data-svs-lead-name="' + row.cells[1].data + '" data-svs-lead-id="' + row.cells[17].data + '">SV Scheduled</a><a class="dropdown-item sv-completed-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#svCompletedRightOffcanvas" aria-controls="rightOffcanvas" data-svc-lead-name="' + row.cells[1].data + '" data-svc-lead-id="' + row.cells[17].data + '">SV Completed</a><a class="dropdown-item eoi-completed-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#eoiCompletedRightOffcanvas" aria-controls="rightOffcanvas" data-eoi-lead-name="' + row.cells[1].data + '" data-eoi-lead-id="' + row.cells[17].data + '">EOI Completed</a><a class="dropdown-item booking-completed-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#bookingCompletedRightOffcanvas" aria-controls="rightOffcanvas" data-booking-lead-name="' + row.cells[1].data + '" data-booking-lead-id="' + row.cells[17].data + '">Booking Completed</a><a class="dropdown-item dead-link" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#deadRightOffcanvas" aria-controls="rightOffcanvas" data-dead-lead-name="' + row.cells[1].data + '" data-dead-lead-id="' + row.cells[17].data + '">Dead Lead</a></div></div>')
            //     }
            // },
// {
//                 name: "Intent",
//                 width: "120px",
//                 formatter: function(e) {
//                     return gridjs.html('<button type="button" class="btn btn-primary">New Lead</button>')
//                 }
//             },
            {
                name: "Intent",
                width: "120px",
                formatter: function(e) {
                    let buttonClass = "btn-primary"; // Default color
            
                    // Change button color based on intent
                    if (e === "Hot") {
                        buttonClass = "btn-danger"; // Red for Hot
                    } else if (e === "Warm") {
                        buttonClass = "btn-warning"; // Yellow/Orange for Warm
                    } else if (e === "Cold") {
                        buttonClass = "btn-info"; // Blue for Cold
                    } else if (!e || e.trim() === "") {
                        buttonClass = "btn-secondary"; // Gray for Blank/No Intent
                    }
            
                    return gridjs.html(`<button type="button" class="btn ${buttonClass}">${e || "New Lead"}</button>`);
                }
            },
            "Source","Assigned User","Created Date","Reasons","Last Note","SV Completed Date",			
            {
                name: "Actions",
                width: "120px",
                formatter: function(e) {
                    return gridjs.html('<li class="list-inline-item fs-20 dropdown d-none d-md-flex"><a href="javascript: void(0);" class="dropdown-toggle arrow-none text-dark show" data-bs-toggle="dropdown" aria-expanded="true"><i class="ri-more-2-fill"></i></a><div class="dropdown-menu dropdown-menu-end"><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">Re-assigned Lead</a><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">View Recent Activity</a><a class="dropdown-item" href="javascript: void(0);" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas">Delete Lead</a></div></li>')
                }
            }
            );
            
            // Initialize the table
        if (window.deadLeadsGrid) {
            // Update the existing Grid.js config
            window.deadLeadsGrid.updateConfig({
                columns,
                server: {
                    url: '<?php echo $base_url;?>dead-ajax-lead-fetch-data.php',
                    params: filters, // Pass the filters object here
                    then: data => data
                }
            }).forceRender(); // This will force a re-render with the new config
        } else {
            // Create a new instance of Grid.js if not already created
            window.deadLeadsGrid = new gridjs.Grid({
                columns,
                pagination: { limit: 100 },
                sort: true,
                search: true,
                server: {
                    url: '<?php echo $base_url;?>dead-ajax-lead-fetch-data.php',
                    params: filters, // Pass the filters object here
                    then: data => data
                }
            });
        
            // Render the new table
            window.deadLeadsGrid.render(document.getElementById("table-gridjs-new-dead"));
        }
        
    }
}
</script>

<script>
// Add this script at the end of your file
document.addEventListener('DOMContentLoaded', function() {
  
    fetch('fetch-projects.php')
      .then(response => response.json())
      .then(projects => {
        const projectCheckboxes = document.getElementById('projectCheckboxes');
        projects.forEach(project => {
          const div = document.createElement('div');
          div.className = 'mb-3 checkbox-container';
          div.innerHTML = `
            <label class="form-check-label" for="project_${project.id}">${project.name}</label>
            <input type="checkbox" class="form-check-input project-checkbox" id="project_${project.id}" value="${project.id}">
          `;
          projectCheckboxes.appendChild(div);
        });
    
        // Attach event listeners RIGHT AFTER appending checkboxes
        document.querySelectorAll('.project-checkbox').forEach(checkbox => {
          checkbox.addEventListener('change', updateSelectedProjectsCount);
        });
    
        // Check for previously selected projects in session
        fetch('handle-project-filter.php', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
          body: 'action=get'
        })
          .then(response => response.json())
          .then(data => {
            if (data.selectedProjects && data.selectedProjects.length > 0) {
              data.selectedProjects.forEach(projectId => {
                const checkbox = document.querySelector(`#project_${projectId}`);
                if (checkbox) {
                  checkbox.checked = true;
                }
              });
              updateSelectedProjectsCount();
            }
          })
          .catch(error => console.error('Error loading saved filters:', error));
      })
      .catch(error => console.error('Error loading projects:', error));


  // Select All Projects
  document.getElementById('selectAllProjects').addEventListener('click', function() {
    document.querySelectorAll('.project-checkbox').forEach(checkbox => {
      checkbox.checked = true;
    });
     updateSelectedProjectsCount();
  });

  // Clear All Projects
  document.getElementById('clearAllProjects').addEventListener('click', function() {
    document.querySelectorAll('.project-checkbox').forEach(checkbox => {
      checkbox.checked = false;
      
    });
    updateSelectedProjectsCount();
    
    // Clear the session
    fetch('handle-project-filter.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: 'action=clear'
    })
    .then(response => response.json())
    .then(data => {
      if (data.status === 'success') {
        // Update lead counts value when apply filter of projects
        // After all grid forceRender() calls
        fetch('get-lead-counters.php')
          .then(res => res.json())
          .then(counterData => {
            // Update each tab label dynamically
            document.querySelector("a[href='#home'] span.d-none.d-sm-block").innerHTML = `All(${counterData.all})`;
            document.querySelector("a[href='#profile'] span.d-none.d-sm-block").innerHTML = `New(${counterData.new})`;
            document.querySelector("a[href='#messages'] span.d-none.d-sm-block").innerHTML = `Followup(${counterData.followup})`;
            document.querySelector("a[href='#svscheduled'] span.d-none.d-sm-block").innerHTML = `SV Scheduled(${counterData.svscheduled})`;
            document.querySelector("a[href='#svcompleted'] span.d-none.d-sm-block").innerHTML = `SV Completed(${counterData.svcompleted})`;
            document.querySelector("a[href='#bookingeois'] span.d-none.d-sm-block").innerHTML = `Booking/EOIs(${counterData.bookingeoi})`;
            document.querySelector("a[href='#dead'] span.d-none.d-sm-block").innerHTML = `Dead(${counterData.dead})`;
          });

        // End Update lead counts value when apply filter of projects
        
        // Refresh the grid to show all data
        if (window.newLeadsGrid) {
          window.newLeadsGrid.forceRender();
        }
        // Refresh the grid with new filters
        if (window.allLeadsGrid) {
          window.allLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.followupLeadsGrid) {
          window.followupLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.svScheduledLeadsGrid) {
          window.svScheduledLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.svCompletedLeadsGrid) {
          window.svCompletedLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.bookingLeadsGrid) {
          window.bookingLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.deadLeadsGrid) {
          window.deadLeadsGrid.forceRender();
        }
      }
    })
    .catch(error => console.error('Error clearing filters:', error));
  });
  
  // Project Search
  document.getElementById('projectSearch').addEventListener('input', function() {
    const searchTerm = this.value.toLowerCase();
    document.querySelectorAll('.checkbox-container').forEach(container => {
      const label = container.querySelector('label').textContent.toLowerCase();
      container.style.display = label.includes(searchTerm) ? '' : 'none';
    });
  });

  // Apply Project Filter
  document.getElementById('applyProjectFilter').addEventListener('click', function() {
    const selectedProjects = Array.from(document.querySelectorAll('.project-checkbox:checked'))
      .map(checkbox => checkbox.value);
    
    // Store selected projects in session
    fetch('handle-project-filter.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: `action=apply&projects=${JSON.stringify(selectedProjects)}`
    })
    .then(response => response.json())
    .then(data => {
      if (data.status === 'success') {
        
        // Update lead counts value when apply filter of projects
        // After all grid forceRender() calls
        fetch('get-lead-counters.php')
          .then(res => res.json())
          .then(counterData => {
            // Update each tab label dynamically
            document.querySelector("a[href='#home'] span.d-none.d-sm-block").innerHTML = `All(${counterData.all})`;
            document.querySelector("a[href='#profile'] span.d-none.d-sm-block").innerHTML = `New(${counterData.new})`;
            document.querySelector("a[href='#messages'] span.d-none.d-sm-block").innerHTML = `Followup(${counterData.followup})`;
            document.querySelector("a[href='#svscheduled'] span.d-none.d-sm-block").innerHTML = `SV Scheduled(${counterData.svscheduled})`;
            document.querySelector("a[href='#svcompleted'] span.d-none.d-sm-block").innerHTML = `SV Completed(${counterData.svcompleted})`;
            document.querySelector("a[href='#bookingeois'] span.d-none.d-sm-block").innerHTML = `Booking/EOIs(${counterData.bookingeoi})`;
            document.querySelector("a[href='#dead'] span.d-none.d-sm-block").innerHTML = `Dead(${counterData.dead})`;
          });

        // End Update lead counts value when apply filter of projects
        
        // Refresh the grid with new filters
        if (window.newLeadsGrid) {
          window.newLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.allLeadsGrid) {
          window.allLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.followupLeadsGrid) {
          window.followupLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.svScheduledLeadsGrid) {
          window.svScheduledLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.svCompletedLeadsGrid) {
          window.svCompletedLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.bookingLeadsGrid) {
          window.bookingLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.deadLeadsGrid) {
          window.deadLeadsGrid.forceRender();
        }
      }
    })
    .catch(error => console.error('Error applying filters:', error));
  });
  
  function updateSelectedProjectsCount() {
      const selectedCount = document.querySelectorAll('.project-checkbox:checked').length;
      const countBadge = document.getElementById('selectedProjectsCount');
       if (selectedCount >= 1) {
        countBadge.textContent = selectedCount;
        countBadge.style.display = 'inline-block';
      } else {
        countBadge.style.display = 'none';
      }
    }
    
    // Load and render status projects
    fetch('fetch-status-projects.php')
      .then(response => response.json())
      .then(projects => {
        const projectCheckboxes = document.getElementById('statusProjectCheckboxes');
        
        // Inject checkboxes
        projects.forEach(project => {
          const div = document.createElement('div');
          div.className = 'mb-3 checkbox-container';
          div.innerHTML = `
            <label class="form-check-label" for="status_project_${project.id}">${project.name}</label>
            <input type="checkbox" class="form-check-input status-project-checkbox" id="status_project_${project.id}" value="${project.id}">
          `;
          projectCheckboxes.appendChild(div);
        });
    
        // Attach change event listeners to checkboxes
        document.querySelectorAll('.status-project-checkbox').forEach(checkbox => {
          checkbox.addEventListener('change', updateSelectedStatusProjectsCount);
        });
    
        // Restore previous selections from session
        fetch('handle-project-filter.php', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
          body: 'action=get'
        })
          .then(response => response.json())
          .then(data => {
            if (data.selectedProjects && data.selectedProjects.length > 0) {
              data.selectedProjects.forEach(projectId => {
                const checkbox = document.querySelector(`#status_project_${projectId}`);
                if (checkbox) {
                  checkbox.checked = true;
                }
              });
              updateSelectedStatusProjectsCount();
            }
          })
          .catch(error => console.error('Error loading saved filters:', error));
      })
      .catch(error => console.error('Error loading projects:', error));
    
    // Select All
    document.getElementById('selectAllStatusProjects').addEventListener('click', () => {
      document.querySelectorAll('.status-project-checkbox').forEach(checkbox => {
        checkbox.checked = true;
      });
      updateSelectedStatusProjectsCount();
    });
    
    // Clear All
    document.getElementById('clearAllStatusProjects').addEventListener('click', () => {
      document.querySelectorAll('.status-project-checkbox').forEach(checkbox => {
        checkbox.checked = false;
      });
      updateSelectedStatusProjectsCount();
    
      // Clear from session
      fetch('handle-project-filter.php', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'action=clearstatusproject'
      })
        .then(response => response.json())
        .then(data => {
          if (data.status === 'success') refreshLeadCountersAndGrids();
        })
        .catch(error => console.error('Error clearing filters:', error));
    });
    
    // Apply Filter
    document.getElementById('applyStatusProjectFilter').addEventListener('click', () => {
      const selectedProjects = Array.from(document.querySelectorAll('.status-project-checkbox:checked')).map(cb => cb.value);
      
      fetch('handle-project-filter.php', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `action=statusporjectapply&statusprojects=${JSON.stringify(selectedProjects)}`
      })
        .then(response => response.json())
        .then(data => {
          if (data.status === 'success') refreshLeadCountersAndGrids();
        })
        .catch(error => console.error('Error applying filters:', error));
    });
    
    // Search
    document.getElementById('statusProjectSearch').addEventListener('input', function () {
      const searchTerm = this.value.toLowerCase();
      document.querySelectorAll('#statusProjectCheckboxes .checkbox-container').forEach(container => {
        const label = container.querySelector('label').textContent.toLowerCase();
        container.style.display = label.includes(searchTerm) ? '' : 'none';
      });
    });
    
    // Badge Count Update
    function updateSelectedStatusProjectsCount() {
      const selectedCount = document.querySelectorAll('.status-project-checkbox:checked').length;
      const countBadge = document.getElementById('selectedStatusProjectsCount');
      if (selectedCount >= 1) {
        countBadge.textContent = selectedCount;
        countBadge.style.display = 'inline-block';
      } else {
        countBadge.style.display = 'none';
      }
    }
    
    // Lead counters and grid refresh (shared function)
    function refreshLeadCountersAndGrids() {
      fetch('get-lead-counters.php')
        .then(res => res.json())
        .then(counterData => {
          document.querySelector("a[href='#home'] span.d-none.d-sm-block").innerHTML = `All(${counterData.all})`;
          document.querySelector("a[href='#profile'] span.d-none.d-sm-block").innerHTML = `New(${counterData.new})`;
          document.querySelector("a[href='#messages'] span.d-none.d-sm-block").innerHTML = `Followup(${counterData.followup})`;
          document.querySelector("a[href='#svscheduled'] span.d-none.d-sm-block").innerHTML = `SV Scheduled(${counterData.svscheduled})`;
          document.querySelector("a[href='#svcompleted'] span.d-none.d-sm-block").innerHTML = `SV Completed(${counterData.svcompleted})`;
          document.querySelector("a[href='#bookingeois'] span.d-none.d-sm-block").innerHTML = `Booking/EOIs(${counterData.bookingeoi})`;
          document.querySelector("a[href='#dead'] span.d-none.d-sm-block").innerHTML = `Dead(${counterData.dead})`;
        });
    
      if (window.newLeadsGrid) window.newLeadsGrid.forceRender();
      if (window.allLeadsGrid) window.allLeadsGrid.forceRender();
      if (window.followupLeadsGrid) window.followupLeadsGrid.forceRender();
      if (window.svScheduledLeadsGrid) window.svScheduledLeadsGrid.forceRender();
      if (window.svCompletedLeadsGrid) window.svCompletedLeadsGrid.forceRender();
      if (window.bookingLeadsGrid) window.bookingLeadsGrid.forceRender();
      if (window.deadLeadsGrid) window.deadLeadsGrid.forceRender();
    }

    
//     fetch('fetch-status-projects.php')
//       .then(response => response.json())
//       .then(projects => {
//         const projectCheckboxes = document.getElementById('statusProjectCheckboxes');
//         projects.forEach(project => {
//           const div = document.createElement('div');
//           div.className = 'mb-3 checkbox-container';
//           div.innerHTML = `
//             <label class="form-check-label" for="status_project_${project.id}">${project.name}</label>
//             <input type="checkbox" class="form-check-input status-project-checkbox" id="status_project_${project.id}" value="${project.id}">
//           `;
//           projectCheckboxes.appendChild(div);
//         });
    
//         // Attach event listeners RIGHT AFTER appending checkboxes
//         document.querySelectorAll('.status_project_checkbox').forEach(checkbox => {
//           checkbox.addEventListener('change', updateSelectedProjectsCount);
//         });
    
//         // Check for previously selected projects in session
//         fetch('handle-project-filter.php', {
//           method: 'POST',
//           headers: {
//             'Content-Type': 'application/x-www-form-urlencoded',
//           },
//           body: 'action=get'
//         })
//           .then(response => response.json())
//           .then(data => {
//             if (data.selectedProjects && data.selectedProjects.length > 0) {
//               data.selectedProjects.forEach(projectId => {
//                 const checkbox = document.querySelector(`#project_${projectId}`);
//                 if (checkbox) {
//                   checkbox.checked = true;
//                 }
//               });
//               updateSelectedProjectsCount();
//             }
//           })
//           .catch(error => console.error('Error loading saved filters:', error));
//       })
//       .catch(error => console.error('Error loading projects:', error));


//   // Select All Projects
//   document.getElementById('selectAllStatusProjects').addEventListener('click', function() {
//     document.querySelectorAll('.status-project-checkbox').forEach(checkbox => {
//       checkbox.checked = true;
//     });
//      updateSelectedProjectsCount();
//   });

//   // Clear All Projects
//   document.getElementById('clearAllStatusProjects').addEventListener('click', function() {
//     document.querySelectorAll('.status-project-checkbox').forEach(checkbox => {
//       checkbox.checked = false;
      
//     });
//     updateSelectedProjectsCount();
    
//     // Clear the session
//     fetch('handle-project-filter.php', {
//       method: 'POST',
//       headers: {
//         'Content-Type': 'application/x-www-form-urlencoded',
//       },
//       body: 'action=clearstatusproject'
//     })
//     .then(response => response.json())
//     .then(data => {
//       if (data.status === 'success') {
//         // Update lead counts value when apply filter of projects
//         // After all grid forceRender() calls
//         fetch('get-lead-counters.php')
//           .then(res => res.json())
//           .then(counterData => {
//             // Update each tab label dynamically
//             document.querySelector("a[href='#home'] span.d-none.d-sm-block").innerHTML = `All(${counterData.all})`;
//             document.querySelector("a[href='#profile'] span.d-none.d-sm-block").innerHTML = `New(${counterData.new})`;
//             document.querySelector("a[href='#messages'] span.d-none.d-sm-block").innerHTML = `Followup(${counterData.followup})`;
//             document.querySelector("a[href='#svscheduled'] span.d-none.d-sm-block").innerHTML = `SV Scheduled(${counterData.svscheduled})`;
//             document.querySelector("a[href='#svcompleted'] span.d-none.d-sm-block").innerHTML = `SV Completed(${counterData.svcompleted})`;
//             document.querySelector("a[href='#bookingeois'] span.d-none.d-sm-block").innerHTML = `Booking/EOIs(${counterData.bookingeoi})`;
//             document.querySelector("a[href='#dead'] span.d-none.d-sm-block").innerHTML = `Dead(${counterData.dead})`;
//           });

//         // End Update lead counts value when apply filter of projects
        
//         // Refresh the grid to show all data
//         if (window.newLeadsGrid) {
//           window.newLeadsGrid.forceRender();
//         }
//         // Refresh the grid with new filters
//         if (window.allLeadsGrid) {
//           window.allLeadsGrid.forceRender();
//         }
        
//         // Refresh the grid with new filters
//         if (window.followupLeadsGrid) {
//           window.followupLeadsGrid.forceRender();
//         }
        
//         // Refresh the grid with new filters
//         if (window.svScheduledLeadsGrid) {
//           window.svScheduledLeadsGrid.forceRender();
//         }
        
//         // Refresh the grid with new filters
//         if (window.svCompletedLeadsGrid) {
//           window.svCompletedLeadsGrid.forceRender();
//         }
        
//         // Refresh the grid with new filters
//         if (window.bookingLeadsGrid) {
//           window.bookingLeadsGrid.forceRender();
//         }
        
//         // Refresh the grid with new filters
//         if (window.deadLeadsGrid) {
//           window.deadLeadsGrid.forceRender();
//         }
//       }
//     })
//     .catch(error => console.error('Error clearing filters:', error));
//   });
  
//   // Project Search
//   document.getElementById('statusProjectSearch').addEventListener('input', function() {
//     const searchTerm = this.value.toLowerCase();
//     document.querySelectorAll('.checkbox-container').forEach(container => {
//       const label = container.querySelector('label').textContent.toLowerCase();
//       container.style.display = label.includes(searchTerm) ? '' : 'none';
//     });
//   });

//   // Apply Project Filter
//   document.getElementById('applyStatusProjectFilter').addEventListener('click', function() {
//     const selectedProjects = Array.from(document.querySelectorAll('.status-project-checkbox:checked'))
//       .map(checkbox => checkbox.value);
    
//     // Store selected projects in session
//     fetch('handle-project-filter.php', {
//       method: 'POST',
//       headers: {
//         'Content-Type': 'application/x-www-form-urlencoded',
//       },
//       body: `action=apply&statusprojects=${JSON.stringify(selectedProjects)}`
//     })
//     .then(response => response.json())
//     .then(data => {
//       if (data.status === 'success') {
        
//         // Update lead counts value when apply filter of projects
//         // After all grid forceRender() calls
//         fetch('get-lead-counters.php')
//           .then(res => res.json())
//           .then(counterData => {
//             // Update each tab label dynamically
//             document.querySelector("a[href='#home'] span.d-none.d-sm-block").innerHTML = `All(${counterData.all})`;
//             document.querySelector("a[href='#profile'] span.d-none.d-sm-block").innerHTML = `New(${counterData.new})`;
//             document.querySelector("a[href='#messages'] span.d-none.d-sm-block").innerHTML = `Followup(${counterData.followup})`;
//             document.querySelector("a[href='#svscheduled'] span.d-none.d-sm-block").innerHTML = `SV Scheduled(${counterData.svscheduled})`;
//             document.querySelector("a[href='#svcompleted'] span.d-none.d-sm-block").innerHTML = `SV Completed(${counterData.svcompleted})`;
//             document.querySelector("a[href='#bookingeois'] span.d-none.d-sm-block").innerHTML = `Booking/EOIs(${counterData.bookingeoi})`;
//             document.querySelector("a[href='#dead'] span.d-none.d-sm-block").innerHTML = `Dead(${counterData.dead})`;
//           });

//         // End Update lead counts value when apply filter of projects
        
//         // Refresh the grid with new filters
//         if (window.newLeadsGrid) {
//           window.newLeadsGrid.forceRender();
//         }
        
//         // Refresh the grid with new filters
//         if (window.allLeadsGrid) {
//           window.allLeadsGrid.forceRender();
//         }
        
//         // Refresh the grid with new filters
//         if (window.followupLeadsGrid) {
//           window.followupLeadsGrid.forceRender();
//         }
        
//         // Refresh the grid with new filters
//         if (window.svScheduledLeadsGrid) {
//           window.svScheduledLeadsGrid.forceRender();
//         }
        
//         // Refresh the grid with new filters
//         if (window.svCompletedLeadsGrid) {
//           window.svCompletedLeadsGrid.forceRender();
//         }
        
//         // Refresh the grid with new filters
//         if (window.bookingLeadsGrid) {
//           window.bookingLeadsGrid.forceRender();
//         }
        
//         // Refresh the grid with new filters
//         if (window.deadLeadsGrid) {
//           window.deadLeadsGrid.forceRender();
//         }
//       }
//     })
//     .catch(error => console.error('Error applying filters:', error));
//   });
  
//   function updateSelectedStatusProjectsCount() {
//       const selectedCount = document.querySelectorAll('.status-project-checkbox:checked').length;
//       const countBadge = document.getElementById('selectedStatusProjectsCount');
//       if (selectedCount >= 1) {
//         countBadge.textContent = selectedCount;
//         countBadge.style.display = 'inline-block';
//       } else {
//         countBadge.style.display = 'none';
//       }
//     }
  
  // Load status projects from database
//   fetch('fetch-status-projects.php')
//     .then(response => response.json())
//     .then(projects => {
//       const projectCheckboxes = document.getElementById('ProjectCheckboxes');
//       projects.forEach(project => {
//         const div = document.createElement('div');
//         div.className = 'mb-3 checkbox-container';
//         div.innerHTML = `
//           <label class="form-check-label" for="status-project_${project.id}">${project.name}</label>
//           <input type="checkbox" class="form-check-input project-checkbox" id="project_${project.id}" value="${project.id}">
//         `;
//         projectCheckboxes.appendChild(div);
//       });

//       // Check for previously selected projects in session
//       fetch('handle-project-filter.php', {
//         method: 'POST',
//         headers: {
//           'Content-Type': 'application/x-www-form-urlencoded',
//         },
//         body: 'action=get'
//       })
//       .then(response => response.json())
//       .then(data => {
//         if (data.selectedProjects && data.selectedProjects.length > 0) {
//           data.selectedProjects.forEach(projectId => {
//             const checkbox = document.querySelector(`#project_${projectId}`);
//             if (checkbox) {
//               checkbox.checked = true;
//             }
//           });
//           updateSelectedStatusProjectsCount();
//         }
//       })
//       .catch(error => console.error('Error loading saved filters:', error));
//       // 🔁 Add checkbox change listeners
    
//     })
//     .catch(error => console.error('Error loading projects:', error));

//     setTimeout(() => {
//       document.querySelectorAll('.project-checkbox').forEach(checkbox => {
//         checkbox.addEventListener('change', updateSelectedProjectsCount);
//       });
//     }, 100);
  
  // Select All Projects
//   document.getElementById('selectAllStatusProjects').addEventListener('click', function() {
//     document.querySelectorAll('.status-project-checkbox').forEach(checkbox => {
//       checkbox.checked = true;
//     });
//      updateSelectedStatusProjectsCount();
//   });

  // Clear All Projects
//   document.getElementById('clearAllStatusProjects').addEventListener('click', function() {
//     document.querySelectorAll('.status-project-checkbox').forEach(checkbox => {
//       checkbox.checked = false;
      
//     });
//     updateSelectedStatusProjectsCount();
    
//     // Clear the session
//     fetch('handle-project-filter.php', {
//       method: 'POST',
//       headers: {
//         'Content-Type': 'application/x-www-form-urlencoded',
//       },
//       body: 'action=clear'
//     })
//     .then(response => response.json())
//     .then(data => {
//       if (data.status === 'success') {
//         // Update lead counts value when apply filter of projects
//         // After all grid forceRender() calls
//         fetch('get-lead-counters.php')
//           .then(res => res.json())
//           .then(counterData => {
//             // Update each tab label dynamically
//             document.querySelector("a[href='#home'] span.d-none.d-sm-block").innerHTML = `All(${counterData.all})`;
//             document.querySelector("a[href='#profile'] span.d-none.d-sm-block").innerHTML = `New(${counterData.new})`;
//             document.querySelector("a[href='#messages'] span.d-none.d-sm-block").innerHTML = `Followup(${counterData.followup})`;
//             document.querySelector("a[href='#svscheduled'] span.d-none.d-sm-block").innerHTML = `SV Scheduled(${counterData.svscheduled})`;
//             document.querySelector("a[href='#svcompleted'] span.d-none.d-sm-block").innerHTML = `SV Completed(${counterData.svcompleted})`;
//             document.querySelector("a[href='#bookingeois'] span.d-none.d-sm-block").innerHTML = `Booking/EOIs(${counterData.bookingeoi})`;
//             document.querySelector("a[href='#dead'] span.d-none.d-sm-block").innerHTML = `Dead(${counterData.dead})`;
//           });

//         // End Update lead counts value when apply filter of projects
        
//         // Refresh the grid to show all data
//         if (window.newLeadsGrid) {
//           window.newLeadsGrid.forceRender();
//         }
//         // Refresh the grid with new filters
//         if (window.allLeadsGrid) {
//           window.allLeadsGrid.forceRender();
//         }
        
//         // Refresh the grid with new filters
//         if (window.followupLeadsGrid) {
//           window.followupLeadsGrid.forceRender();
//         }
        
//         // Refresh the grid with new filters
//         if (window.svScheduledLeadsGrid) {
//           window.svScheduledLeadsGrid.forceRender();
//         }
        
//         // Refresh the grid with new filters
//         if (window.svCompletedLeadsGrid) {
//           window.svCompletedLeadsGrid.forceRender();
//         }
        
//         // Refresh the grid with new filters
//         if (window.bookingLeadsGrid) {
//           window.bookingLeadsGrid.forceRender();
//         }
        
//         // Refresh the grid with new filters
//         if (window.deadLeadsGrid) {
//           window.deadLeadsGrid.forceRender();
//         }
//       }
//     })
//     .catch(error => console.error('Error clearing filters:', error));
//   });
  
  // Status Project Search
//   document.getElementById('statusProjectSearch').addEventListener('input', function() {
//     const searchTerm = this.value.toLowerCase();
//     document.querySelectorAll('.checkbox-container').forEach(container => {
//       const label = container.querySelector('label').textContent.toLowerCase();
//       container.style.display = label.includes(searchTerm) ? '' : 'none';
//     });
//   });
  
  // Apply Status Project Filter
//   document.getElementById('applyStatusProjectFilter').addEventListener('click', function() {
//     const selectedProjects = Array.from(document.querySelectorAll('.status-project-checkbox:checked'))
//       .map(checkbox => checkbox.value);
    
//     // Store selected projects in session
//     fetch('handle-project-filter.php', {
//       method: 'POST',
//       headers: {
//         'Content-Type': 'application/x-www-form-urlencoded',
//       },
//       body: `action=applystatus&statusprojects=${JSON.stringify(selectedProjects)}`
//     })
//     .then(response => response.json())
//     .then(data => {
//       if (data.status === 'success') {
        
//         // Update lead counts value when apply filter of projects
//         // After all grid forceRender() calls
//         fetch('get-lead-counters.php')
//           .then(res => res.json())
//           .then(counterData => {
//             // Update each tab label dynamically
//             document.querySelector("a[href='#home'] span.d-none.d-sm-block").innerHTML = `All(${counterData.all})`;
//             document.querySelector("a[href='#profile'] span.d-none.d-sm-block").innerHTML = `New(${counterData.new})`;
//             document.querySelector("a[href='#messages'] span.d-none.d-sm-block").innerHTML = `Followup(${counterData.followup})`;
//             document.querySelector("a[href='#svscheduled'] span.d-none.d-sm-block").innerHTML = `SV Scheduled(${counterData.svscheduled})`;
//             document.querySelector("a[href='#svcompleted'] span.d-none.d-sm-block").innerHTML = `SV Completed(${counterData.svcompleted})`;
//             document.querySelector("a[href='#bookingeois'] span.d-none.d-sm-block").innerHTML = `Booking/EOIs(${counterData.bookingeoi})`;
//             document.querySelector("a[href='#dead'] span.d-none.d-sm-block").innerHTML = `Dead(${counterData.dead})`;
//           });

//         // End Update lead counts value when apply filter of projects
        
//         // Refresh the grid with new filters
//         if (window.newLeadsGrid) {
//           window.newLeadsGrid.forceRender();
//         }
        
//         // Refresh the grid with new filters
//         if (window.allLeadsGrid) {
//           window.allLeadsGrid.forceRender();
//         }
        
//         // Refresh the grid with new filters
//         if (window.followupLeadsGrid) {
//           window.followupLeadsGrid.forceRender();
//         }
        
//         // Refresh the grid with new filters
//         if (window.svScheduledLeadsGrid) {
//           window.svScheduledLeadsGrid.forceRender();
//         }
        
//         // Refresh the grid with new filters
//         if (window.svCompletedLeadsGrid) {
//           window.svCompletedLeadsGrid.forceRender();
//         }
        
//         // Refresh the grid with new filters
//         if (window.bookingLeadsGrid) {
//           window.bookingLeadsGrid.forceRender();
//         }
        
//         // Refresh the grid with new filters
//         if (window.deadLeadsGrid) {
//           window.deadLeadsGrid.forceRender();
//         }
//       }
//     })
//     .catch(error => console.error('Error applying filters:', error));
//   });

  
    
    // function updateSelectedStatusProjectsCount() {
    //   const selectedCount = document.querySelectorAll('.status-project-checkbox:checked').length;
    //   const countBadge = document.getElementById('selectedStatusProjectsCount');
    //   if (selectedCount >= 1) {
    //     countBadge.textContent = selectedCount;
    //     countBadge.style.display = 'inline-block';
    //   } else {
    //     countBadge.style.display = 'none';
    //   }
    // }
    
    function updateSelectedAssignedToCount() {
      const selectedCount = document.querySelectorAll('.ass-user-checkbox:checked').length;
      const countBadge = document.getElementById('selectedAssignedToCount');
       if (selectedCount >= 1) {
        countBadge.textContent = selectedCount;
        countBadge.style.display = 'inline-block';
      } else {
        countBadge.style.display = 'none';
      }
    }
  
   // Load Assigned user from database
//   fetch('fetch-assigned-user.php')
//     .then(response => response.json())
//     .then(projects => {
//       const projectCheckboxes = document.getElementById('assignedUserCheckboxes');
//       projects.forEach(project => {
//         const div = document.createElement('div');
//         div.className = 'mb-3 checkbox-container';
//         div.innerHTML = `
//           <label class="form-check-label" for="assigneduser_${project.id}">${project.name}</label>
//           <input type="checkbox" class="form-check-input ass-user-checkbox" id="assigneduser_${project.id}" value="${project.id}">
//         `;
//         projectCheckboxes.appendChild(div);
//       });
      
//     //   // Add change listeners to update count on checkbox toggle
//     //     setTimeout(() => {
//     //       document.querySelectorAll('.project-checkbox').forEach(checkbox => {
//     //         checkbox.addEventListener('change', updateSelectedProjectsCount);
//     //       });
        
//     //       // Initial update of count after loading
//     //       updateSelectedProjectsCount();
//     //     }, 100);

//       // Check for previously selected projects in session
//       fetch('handle-assigned-user-filter.php', {
//         method: 'POST',
//         headers: {
//           'Content-Type': 'application/x-www-form-urlencoded',
//         },
//         body: 'action=get'
//       })
//       .then(response => response.json())
//       .then(data => {
//         if (data.selectedProjects && data.selectedProjects.length > 0) {
//           data.selectedProjects.forEach(projectId => {
//             const checkbox = document.querySelector(`#assigneduser_${projectId}`);
//             if (checkbox) {
//               checkbox.checked = true;
//             }
//           });
//           updateSelectedAssignedToCount();
//         }
//       })
//       .catch(error => console.error('Error loading saved filters:', error));
//     })
//     .catch(error => console.error('Error loading projects:', error));
    
//     setTimeout(() => {
//       document.querySelectorAll('.ass-user-checkbox').forEach(checkbox => {
//         checkbox.addEventListener('change', updateSelectedAssignedToCount);
//       });
//     }, 100);

    fetch('fetch-assigned-user.php')
      .then(response => response.json())
      .then(users => {
        const container = document.getElementById('assignedUserCheckboxes');
        users.forEach(user => {
          const div = document.createElement('div');
          div.className = 'mb-3 checkbox-container';
          div.innerHTML = `
            <label class="form-check-label" for="assigneduser_${user.id}">${user.name}</label>
            <input type="checkbox" class="form-check-input ass-user-checkbox" id="assigneduser_${user.id}" value="${user.id}">
          `;
          container.appendChild(div);
        });
    
        // 🔁 Attach change listeners immediately after DOM is updated
        document.querySelectorAll('.ass-user-checkbox').forEach(checkbox => {
          checkbox.addEventListener('change', updateSelectedAssignedToCount);
        });
    
        // Load previously selected filters from session
        fetch('handle-assigned-user-filter.php', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
          body: 'action=get'
        })
          .then(response => response.json())
          .then(data => {
            if (data.selectedProjects && data.selectedProjects.length > 0) {
              data.selectedProjects.forEach(projectId => {
                const checkbox = document.querySelector(`#assigneduser_${projectId}`);
                if (checkbox) {
                  checkbox.checked = true;
                }
              });
              updateSelectedAssignedToCount();
            }
          })
          .catch(error => console.error('Error loading saved filters:', error));
      })
      .catch(error => console.error('Error loading assigned users:', error));

    
    // Select All Projects
  document.getElementById('selectAllAssignedUser').addEventListener('click', function() {
    document.querySelectorAll('.ass-user-checkbox').forEach(checkbox => {
      checkbox.checked = true;
    });
    updateSelectedAssignedToCount();
  });

  // Clear All Projects
  document.getElementById('clearAllAssignedUser').addEventListener('click', function() {
    document.querySelectorAll('.ass-user-checkbox').forEach(checkbox => {
      checkbox.checked = false;
    });
    updateSelectedAssignedToCount();
    
    // Clear the session
    fetch('handle-project-filter.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: 'action=clearassigneduser'
    })
    .then(response => response.json())
    .then(data => {
      if (data.status === 'success') {
         // Update lead counts value when apply filter of projects
        // After all grid forceRender() calls
        fetch('get-lead-counters.php')
          .then(res => res.json())
          .then(counterData => {
            // Update each tab label dynamically
            document.querySelector("a[href='#home'] span.d-none.d-sm-block").innerHTML = `All(${counterData.all})`;
            document.querySelector("a[href='#profile'] span.d-none.d-sm-block").innerHTML = `New(${counterData.new})`;
            document.querySelector("a[href='#messages'] span.d-none.d-sm-block").innerHTML = `Followup(${counterData.followup})`;
            document.querySelector("a[href='#svscheduled'] span.d-none.d-sm-block").innerHTML = `SV Scheduled(${counterData.svscheduled})`;
            document.querySelector("a[href='#svcompleted'] span.d-none.d-sm-block").innerHTML = `SV Completed(${counterData.svcompleted})`;
            document.querySelector("a[href='#bookingeois'] span.d-none.d-sm-block").innerHTML = `Booking/EOIs(${counterData.bookingeoi})`;
            document.querySelector("a[href='#dead'] span.d-none.d-sm-block").innerHTML = `Dead(${counterData.dead})`;
          });

        // End Update lead counts value when apply filter of projects
        // Refresh the grid to show all data
        if (window.newLeadsGrid) {
          window.newLeadsGrid.forceRender();
        }
        // Refresh the grid with new filters
        if (window.allLeadsGrid) {
          window.allLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.followupLeadsGrid) {
          window.followupLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.svScheduledLeadsGrid) {
          window.svScheduledLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.svCompletedLeadsGrid) {
          window.svCompletedLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.bookingLeadsGrid) {
          window.bookingLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.deadLeadsGrid) {
          window.deadLeadsGrid.forceRender();
        }
        
      }
    })
    .catch(error => console.error('Error clearing filters:', error));
  });

  // Project Search
  document.getElementById('assignedUserSearch').addEventListener('input', function() {
    const searchTerm = this.value.toLowerCase();
    document.querySelectorAll('.checkbox-container').forEach(container => {
      const label = container.querySelector('label').textContent.toLowerCase();
      container.style.display = label.includes(searchTerm) ? '' : 'none';
    });
  });

  // Apply Assigned User Filter
  document.getElementById('applyAssignedUserFilter').addEventListener('click', function() {
    const selectedProjects = Array.from(document.querySelectorAll('.ass-user-checkbox:checked'))
      .map(checkbox => checkbox.value);
    
    // Store selected projects in session
    fetch('handle-project-filter.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: `action=assigneduserapply&assigneduser=${JSON.stringify(selectedProjects)}`
    })
    .then(response => response.json())
    .then(data => {
      if (data.status === 'success') {
          
        // Update lead counts value when apply filter of Assigned user
        // After all grid forceRender() calls
        fetch('get-lead-counters.php')
          .then(res => res.json())
          .then(counterData => {
            // Update each tab label dynamically
            document.querySelector("a[href='#home'] span.d-none.d-sm-block").innerHTML = `All(${counterData.all})`;
            document.querySelector("a[href='#profile'] span.d-none.d-sm-block").innerHTML = `New(${counterData.new})`;
            document.querySelector("a[href='#messages'] span.d-none.d-sm-block").innerHTML = `Followup(${counterData.followup})`;
            document.querySelector("a[href='#svscheduled'] span.d-none.d-sm-block").innerHTML = `SV Scheduled(${counterData.svscheduled})`;
            document.querySelector("a[href='#svcompleted'] span.d-none.d-sm-block").innerHTML = `SV Completed(${counterData.svcompleted})`;
            document.querySelector("a[href='#bookingeois'] span.d-none.d-sm-block").innerHTML = `Booking/EOIs(${counterData.bookingeoi})`;
            document.querySelector("a[href='#dead'] span.d-none.d-sm-block").innerHTML = `Dead(${counterData.dead})`;
          });

        // End Update lead counts value when apply filter of projects
        // Refresh the grid with new filters
        if (window.newLeadsGrid) {
          window.newLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.allLeadsGrid) {
          window.allLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.followupLeadsGrid) {
          window.followupLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.svScheduledLeadsGrid) {
          window.svScheduledLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.svCompletedLeadsGrid) {
          window.svCompletedLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.bookingLeadsGrid) {
          window.bookingLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.deadLeadsGrid) {
          window.deadLeadsGrid.forceRender();
        }
      }
    })
    .catch(error => console.error('Error applying filters:', error));
  });
  

  document.getElementById('applyCreatedDateFilter').addEventListener('click', function () {
  const selectedDateOption = document.querySelector('input[name="dateFilter"]:checked');
  const startDate = document.getElementById('basic-datepicker-start').value;
  const endDate = document.getElementById('basic-datepicker-end').value;

  let payload = {
    action: 'createddateapply',
    dateOption: selectedDateOption ? selectedDateOption.value : '',
    startDate: startDate,
    endDate: endDate
  };

  fetch('handle-project-filter.php', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: new URLSearchParams(payload).toString()
  })
    .then(response => response.json())
    .then(data => {
      if (data.status === 'success') {
        // Update lead counts value when apply filter of projects
        // After all grid forceRender() calls
        fetch('get-lead-counters.php')
          .then(res => res.json())
          .then(counterData => {
            // Update each tab label dynamically
            document.querySelector("a[href='#home'] span.d-none.d-sm-block").innerHTML = `All(${counterData.all})`;
            document.querySelector("a[href='#profile'] span.d-none.d-sm-block").innerHTML = `New(${counterData.new})`;
            document.querySelector("a[href='#messages'] span.d-none.d-sm-block").innerHTML = `Followup(${counterData.followup})`;
            document.querySelector("a[href='#svscheduled'] span.d-none.d-sm-block").innerHTML = `SV Scheduled(${counterData.svscheduled})`;
            document.querySelector("a[href='#svcompleted'] span.d-none.d-sm-block").innerHTML = `SV Completed(${counterData.svcompleted})`;
            document.querySelector("a[href='#bookingeois'] span.d-none.d-sm-block").innerHTML = `Booking/EOIs(${counterData.bookingeoi})`;
            document.querySelector("a[href='#dead'] span.d-none.d-sm-block").innerHTML = `Dead(${counterData.dead})`;
          });

        // End Update lead counts value when apply filter of projects
        if (window.newLeadsGrid) window.newLeadsGrid.forceRender();
        if (window.allLeadsGrid) window.allLeadsGrid.forceRender();
        
        // Refresh the grid with new filters
        if (window.followupLeadsGrid) {
          window.followupLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.svScheduledLeadsGrid) {
          window.svScheduledLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.svCompletedLeadsGrid) {
          window.svCompletedLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.bookingLeadsGrid) {
          window.bookingLeadsGrid.forceRender();
        }
        
        // Refresh the grid with new filters
        if (window.deadLeadsGrid) {
          window.deadLeadsGrid.forceRender();
        }
        // ...add other grids if needed
      }
    })
    .catch(error => console.error('Error applying date filter:', error));
    });

    // Clear created date filters
    document.getElementById('clearCreatedDate').addEventListener('click', function () {
      document.querySelectorAll('input[name="dateFilter"]').forEach(r => r.checked = false);
      document.getElementById('basic-datepicker-start').value = '';
      document.getElementById('basic-datepicker-end').value = '';
    
      fetch('handle-project-filter.php', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'action=clearcreateddate'
      })
        .then(response => response.json())
        .then(data => {
          if (data.status === 'success') {
            // Update lead counts value when apply filter of projects
        // After all grid forceRender() calls
        fetch('get-lead-counters.php')
          .then(res => res.json())
          .then(counterData => {
            // Update each tab label dynamically
            document.querySelector("a[href='#home'] span.d-none.d-sm-block").innerHTML = `All(${counterData.all})`;
            document.querySelector("a[href='#profile'] span.d-none.d-sm-block").innerHTML = `New(${counterData.new})`;
            document.querySelector("a[href='#messages'] span.d-none.d-sm-block").innerHTML = `Followup(${counterData.followup})`;
            document.querySelector("a[href='#svscheduled'] span.d-none.d-sm-block").innerHTML = `SV Scheduled(${counterData.svscheduled})`;
            document.querySelector("a[href='#svcompleted'] span.d-none.d-sm-block").innerHTML = `SV Completed(${counterData.svcompleted})`;
            document.querySelector("a[href='#bookingeois'] span.d-none.d-sm-block").innerHTML = `Booking/EOIs(${counterData.bookingeoi})`;
            document.querySelector("a[href='#dead'] span.d-none.d-sm-block").innerHTML = `Dead(${counterData.dead})`;
          });

        // End Update lead counts value when apply filter of projects
            if (window.newLeadsGrid) window.newLeadsGrid.forceRender();
            if (window.allLeadsGrid) window.allLeadsGrid.forceRender();
            
            // Refresh the grid with new filters
            if (window.followupLeadsGrid) {
              window.followupLeadsGrid.forceRender();
            }
            
            // Refresh the grid with new filters
            if (window.svScheduledLeadsGrid) {
              window.svScheduledLeadsGrid.forceRender();
            }
            
            // Refresh the grid with new filters
            if (window.svCompletedLeadsGrid) {
              window.svCompletedLeadsGrid.forceRender();
            }
            
            // Refresh the grid with new filters
            if (window.bookingLeadsGrid) {
              window.bookingLeadsGrid.forceRender();
            }
            
            // Refresh the grid with new filters
            if (window.deadLeadsGrid) {
              window.deadLeadsGrid.forceRender();
            }
          }
        })
        .catch(error => console.error('Error clearing date filter:', error));
    });


});
</script>