<?php
require('header.php');
session_start();
include "dbconfig.php";
$link =opencon();


if(isset($_POST['save']))
{
        
		$inids=$_POST['ids'];
		
		$date=date("Y-m-d");
		
		$count=count($_POST['ids']);
		for($i=0;$i<$count;$i++)
		{
		   $inid=$inids[$i];
		
		$v1 = $inid;
        $v2 = $_POST['staff'];
      
        
			 
$sql="UPDATE new_leads SET 	assigned_to='$v2',assigned_date='$date' WHERE id='$v1'";


 mysqli_query($link,$sql);

if($i==($count-1))
{
    echo "<script>alert('Assigned success')</script>";
}



		}
	


}
?><link rel="stylesheet" href="css/summernote.css" />
<style>
     .btn-group {
        text-align: center;
        margin-bottom: 15px;
        margin-left: 1%;
    }
    .btn-option {
        padding: 10px 20px;
        border-radius: 5px;
        border: 1px solid #ddd;
        background-color: #fff;
        cursor: pointer;
        font-size: 16px;
        margin: 5px;
    }
    .btn-option.active {
        background-color: #007bff;
        color: #fff;
    }
     .preview-box {
        text-align: center;
        padding: 15px;
        border: 1px solid #ddd;
        border-radius: 8px;
        margin-bottom: 15px;
        display: none;
    }
    .preview-box img {
        max-width: 100%;
        height: auto;
        border-radius: 8px;
        margin-top: 10px;
    }
    
        .form-container {
        display: none;
    }
    .form-container.active {
        display: block;
    }
    .container-box {
        background: #f8f9fa;
        padding: 20px;
        border-radius: 8px;
        margin-bottom: 20px;
    }
</style>
<div class="breadcome-area mg-b-30 small-dn">
                <div class="container-fluid">
                    <div class="row">

                                                
                        <div class="col-lg-12">
                            <div class="breadcome-list shadow-reset">
                                <div class="row">
                             <div class="col-lg-12">
                                 <!--<h4 style="text-align: center;font-size: 26px;background-color: antiquewhite;height: 36px;margin-top: -20px;">Search</h4>-->
                                  </div>
                               </div>
                                
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Breadcome End-->
          
             <div class="btn-group">
                    <button class="btn-option active" onclick="toggleSection('mailForm')">Mail</button>
                    <button class="btn-option" onclick="toggleSection('whatsappForm')">WhatsApp</button>
                </div>
          <div id="mailForm" class="form-container  container-box">
                    <h4 class="title">Send Mail</h4>
                    <form>
                        <div class="form-group">
                            <label>To</label>
                            <input type="text" class="form-control" id="to_email" placeholder="Recipient Emails (comma-separated)">
                        </div>
                        <div class="form-group">
                            <label>CC</label>
                            <input type="text" class="form-control" id="cc_email" placeholder="CC Emails (optional)">
                        </div>
                        <div class="form-group">
                            <label>BCC</label>
                            <input type="text" class="form-control" id="bcc_email" placeholder="BCC Emails (optional)">
                        </div>
                        <div class="form-group">
                            <label>Subject</label>
                            <input type="text" class="form-control" id="mail_subject" placeholder="Enter Email Subject">
                        </div>
                        <div class="form-group">
                            <label>Message</label>
                            <textarea id="summernote2" class="form-control"></textarea>
                        </div>
                        <div class="form-group">
                            <label>Poster</label>
                         <select id="filterTemplate" class="form-control" onchange="updateTemplatePreview()">
    <option value="">Select</option>
    <?php
    $sql = "SELECT * FROM templates";
    $sql_exe = mysqli_query($link, $sql);
    while ($fetch_qr = mysqli_fetch_array($sql_exe)) {
        echo "<option value='{$fetch_qr['id']}' data-img='{$fetch_qr['image']}' data-folder='templates/' data-file='{$fetch_qr['image']}'>
                Template {$fetch_qr['id']}
              </option>";
    }
    ?>
</select>

                        </div>
                        <button type="button" class="btn btn-primary btn-block" onclick="sendBulkMail()">Send Bulk Mail</button>
                    </form>
                </div>

                <!-- WhatsApp Form -->
             <div id="whatsappForm" class="form-container container-box">
    <h4 class="title">Send WhatsApp Template Message</h4>
    <form id="whatsappMessageForm">
        <div class="form-group">
            <label>Recipient Number (Manual Entry)</label>
            <input type="text" class="form-control" id="whatsapp_number" placeholder="e.g., +919876543210">
        </div>
        <div class="form-group">
            <label>Template Name</label>
            <select id="template_name" class="form-control">
                <option value="">Loading templates...</option>
            </select>
            <input type="hidden" class="form-control" id="template_language" value="ta">
        </div>
        <div class="form-group">
            <label>Upload Image</label>
            <input type="file" class="form-control" id="image_upload">
        </div>
        <input type="hidden" id="image_url"> <!-- Hidden field to store uploaded image URL -->
        <button type="button" class="btn btn-primary btn-block" onclick="uploadImage()">Upload & Send</button>
    </form>
</div>

                <!-- Template Preview -->
                <div id="templatePreview" class="container-box preview-box">
                    <h4 class="title">Template Preview</h4>
                    <p id="templateDetails"></p>
                       <p id="attachments"></p>
                    <img id="templateImage" src="" alt="Template Image">
                </div>
            <!-- stockprice, feed area end-->
            <div class="admin-dashone-data-table-area mg-b-15">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="sparkline8-list shadow-reset">
                                <div class="sparkline8-hd">
                                    <div class="main-sparkline8-hd">
                                        <h1>Lead List</h1>
                                        <div class="sparkline8-outline-icon">
                                            <span class="sparkline8-collapse-link"><i class="fa fa-chevron-up"></i></span>
                                            <span><i class="fa fa-wrench"></i></span>
                                            <span class="sparkline8-collapse-close"><i class="fa fa-times"></i></span>
                                        </div>
                                    </div>
                                </div>
                                
                                <?php
                                if( $_SESSION["session_id"]==1 || $_SESSION["session_id"]==24 || $_SESSION["session_id"]==25)
                                {
                                    ?>
                                     <div class="sparkline12-graph">
                                    <div class="basic-login-form-ad">
                                        <div class="row">
                                            <div class="col-lg-12">
                                                <div class="all-form-element-inner">
                                      
                                                        <div class="form-group-inner">
                                                            <div class="row">
                                                                <div class="col-lg-3">
                                                                    <label class="login2 pull-right pull-right-pro">Assigned To</label>
                                                                </div>
                                                                <div class="col-lg-4">
                                                                    
                                                  <select type="text" class="form-control" name="staffname" id="convert_telecaller" onchange="setvalue(this.value)">
                                                                          <option value="" >Select </option>
                                                                         <?php 
                                                      
   echo file_get_contents("https://hrdandrecruitments.com/hr/tm_tl_tc_drop.php?".urlencode($where1.$where2.$where3)."");
    ?>
   <option value="ROSHNI G" >ROSHNI G</option>
   <option value="RAJESWARI S" >RAJESWARI S</option>
                                                                        
                                                                    </select>                    
                                                                    
                                                                   
                                                                </div>
                                                            </div>
                                                        </div>
                                                                                                              
														
                                                        <div class="form-group-inner">
                                                            <div class="login-btn-inner">
                                                                <div class="row">
                                                                    <div class="col-lg-3"></div>
                                                                    <div class="col-lg-9">
                                                                        <div class="login-horizental cancel-wp pull-left">
                                        <button class="btn btn-sm btn-primary login-submit-cs"  onclick="trigfunction('savewillpay')">Assign</button>
                                        
                                       
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                             
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                    <?php
                                }
                                ?>
                                  
                                <div class="sparkline8-graph">
                                    <div class="datatable-dashv1-list custom-datatable-overright">
                                        <div id="toolbar">
                                            <select class="form-control">
                                                <option value="">Export Basic</option>
                                                <option value="all">Export All</option>
                                                <option value="selected">Export Selected</option>
                                            </select>
                                        </div>
                                        
                                        
                                          <form method="post"> 
                                          
                                        <table id="table" data-toggle="table" data-pagination="true" data-search="true" data-show-columns="true" data-show-pagination-switch="true" data-show-refresh="true" data-key-events="true" data-show-toggle="true" data-resizable="true" data-cookie="true" data-cookie-id-table="saveId" data-show-export="true" data-click-to-select="true" data-toolbar="#toolbar">
                                            <thead>
                                                <tr >
                                                      <th><input type='checkbox' id='checkAll' style="margin-top: 2px" onclick="checkall(this)">CHECK ALL</th>
                                            <th >S.No</th>
                                            <th>Assigned Date</th>
                                            <th>Lead Type</th>
                                            <th>sub Lead Type</th>

     
     
                                            
<th>Lead Given Date</th>
<th>Lead Status</th>
<th>Lead Enquiry For</th>
<th>Client Name</th>
<th>Client Number</th>
<th>Client Email</th>
<th>Client Location</th>


<th>Client Job Type</th>

<th>Designation</th>
<th>Salary Per Month</th>

<th>Property Type</th>

<th>Total Cents</th>
<th>Per Cent - Budget</th>
<th>Home - Budget</th>
<th>Total - Budget</th>
<th>Lead Generated By</th>
<th>Assigned To</th>
<th>Telecaller</th>
<th>Team Manager</th>


                                           
   <th>Action</th>                                       
                                        </tr>
                                            </thead>
                                             <tbody id="myTable">
<?php

$session=$_GET['session'];

$sql107=explode("[]",$_SESSION[$session]);

if(isset($_GET['page']))
{
    
      if($_SESSION["fullname"]!="Pashmi" && $_SESSION["fullname"]!="Samboorna")
{
    $team_con=" and team_manager='".$_SESSION["fullname"]."'";
}
    
    
    $page=$_GET['page'];
    

  $tm=$_GET['team_manager'];  
$tele=$_GET['telecaller'];  
// Apply filters dynamically
if (!empty($_GET['telecaller'])) {
    $telecaller = mysqli_real_escape_string($link, $_GET['telecaller']);
    $where1 = " AND telecaller = '$telecaller'";
}

if (!empty($_GET['team_manager'])) {
    $team_manager = mysqli_real_escape_string($link, $_GET['team_manager']);
    $where2 = " AND team_manager = '$team_manager'";
}

if(isset($_GET['telecaller']) && $tm=="" && !isset($_GET['total']) && !isset($_GET['subtotal']))
{
    $where1 = " AND telecaller = ''";
}
else if(isset($_GET['telecaller']) && $tm=="" && !isset($_GET['total']) && isset($_GET['subtotal']))
{
    $where1 = " AND telecaller = ''";
}
else if(!empty($_GET['telecaller']))
{
    $telecaller = mysqli_real_escape_string($link, $_GET['telecaller']);
    $where1 = " AND telecaller = '$telecaller'";
}


if(isset($_GET['team_manager']) && $tm=="" && !isset($_GET['total']) && !isset($_GET['subtotal']))
{
    $where2 = " AND team_manager = ''";
}
else if(isset($_GET['team_manager']) && $tm=="" && !isset($_GET['total']) && isset($_GET['subtotal']))
{
    $where2 = " AND team_manager = ''";
}
else if(!empty($_GET['team_manager']))
{
    $team_manager = mysqli_real_escape_string($link, $_GET['team_manager']);
    $where2 = " AND team_manager = '$team_manager'";
}

if (!empty($_GET['status'])) {
    $status = mysqli_real_escape_string($link, $_GET['status']);
    $where3 = " AND client_status = '$status'";
}
$date_wise1=$_SESSION['date_wise1'];
if (!empty($_GET['date_range'])) {
    $date_range = $_GET['date_range'];
    if ($date_range == "till_yesterday") {
        $where4 = " AND (".$date_wise1." < CURDATE() or ".$date_wise1."='0000-00-00')";
    } elseif ($date_range == "today") {
        $where4 = " AND ".$date_wise1." = CURDATE()";
    } elseif ($date_range == "total") {
        // No extra condition needed for total, as it includes all dates
    }
}
if (!empty($_GET['sub_lead_type'])) {
    $sub_lead_type = mysqli_real_escape_string($link, $_GET['sub_lead_type']);
    $where5 = " AND sub_lead_type = '$sub_lead_type'";
}


if($page=="1")
    {
        $query = "SELECT * 
          FROM new_leads 
          WHERE id!=''  
          AND (lead_type='ORGANIC LEADS' OR lead_type='CAMPAIGN LEADS') 
          AND sub_lead_type NOT IN ('', 'Bulk lead', 'Retail lead') 
          AND call_status='Connected' 
          AND lead_status='Interested' $team_con $where1 $where2 $where3 $where4 $where5";
    }
    else
    {
        $query = "SELECT *
          FROM new_leads 
          WHERE id!=''  
          AND (lead_type='ORGANIC LEADS' OR lead_type='CAMPAIGN LEADS') 
          AND sub_lead_type  IN ('Retail lead') 
          AND call_status='Connected' 
          AND lead_status='Interested' $team_con $where1 $where2 $where3 $where4 $where5";
    }

// echo $query;

$sql107=explode("[]",$query."[]");

}

$count=count($sql107);

$prabuinc=0;
$count1=1;
while($prabuinc < $count)
{
    $sql108=$sql107[$prabuinc];
// echo $sql108."<br>";
if($sql108!='')
{

$sql_exe = mysqli_query($link,$sql108);
$num_rows=mysqli_num_rows($sql_exe);
if($num_rows > 0 )
{
       while($fetch_qr = mysqli_fetch_array($sql_exe)){
           
$ids=$fetch_qr['id'];
?>
 <tr>
     <td>
<input type='checkbox' class='check-input' name='ids[]' value='<?php echo $ids;?>'>

</td>
                            <td ><?php echo $count1; ?></td>
                             <td ><?php echo $fetch_qr['assigned_date']; ?></td>
                             <td ><?php echo $fetch_qr['lead_type']; ?></td>
                             <td ><?php echo $fetch_qr['sub_lead_type']; ?></td>
                            
                            <td ><?php echo $fetch_qr['lead_given_date']; ?></td>
                        
                           <?php
                           $mainid=$ids;
                           ?>


<td>
    <div style="display:flex">
    <div>
            <?php
if($_SESSION["fullname"]=="SWATHIKA" || $_SESSION["fullname"]=="GOBIKA")
{
    echo $fetch_qr["constructive"]."-".$fetch_qr["constructive_re"];
   
}
else
{
 ?>
 <select name='call_status' class='form-control call_status1<?=$count1;?> ' style='width: 167px;' onchange="updateQueryStatus1(this.value, <?=$count1;?>)">
                         <?php
                         if($fetch_qr["constructive"]!='')
                         {
                         ?>
                         
                         <option value="<?=$fetch_qr["constructive"];?>"><?=$fetch_qr["constructive"];?></option>
                         
                         <?php
                         }
                         ?>

<option value="">Select</option>
<option value="Constructive">Constructive</option>

<option value="Non Constructive">Non Constructive</option>


</select>
    <br>
<select name='lead_status' class='form-control lead_status1<?=$count1;?> ' style='width: 167px;'>
                         <?php
                         if($fetch_qr["constructive_re"]!='')
                         {
                         ?>
                         
                         <option value="<?=$fetch_qr["constructive_re"];?>"><?=$fetch_qr["constructive_re"];?></option>
                         
                         <?php
                         }
                         ?>

<option value="">Select</option>

<option value="Not relevant">Not relevant</option>


<option value="No not available">No not available</option>

</select>

<button type="button" id='basicSuccessAnimation' class='btn btn-success query_statusubmit$i trigger'  onclick=submitapproval_call2('<?=$mainid;?>',this,<?=$count1;?>)  style='margin-top: 10%;'>submit</button>
 <?php
}
?>
    </div>
    <div style="margin-left:10px">
        
    <select name='call_status' class='form-control call_status<?=$count1;?> ' style='width: 167px;'>
                         <?php
                         if($fetch_qr["call_status"]!='')
                         {
                         ?>
                         
                         <option value="<?=$fetch_qr["call_status"];?>"><?=$fetch_qr["call_status"];?></option>
                         
                         <?php
                         }
                         ?>

<option value="">Select</option>
<option value="Connected">Connected</option>

<option value="Not connected">Not connected</option>


</select>
<br>
    
    <select name='lead_status' class='form-control lead_status<?=$count1;?> ' style='width: 167px;' onchange="updateQueryStatus(this.value, <?=$count1;?>)">
                         <?php
                         if($fetch_qr["lead_status"]!='')
                         {
                         ?>
                
                         <option value="<?=$fetch_qr["lead_status"];?>"><?=$fetch_qr["lead_status"];?></option>
                         
                         <?php
                         }
                         ?>

<option value="">Select</option>

<option value="Interested">Interested</option>


<option value="Not Interested">Not Interested</option>

</select>
<br>
  <select name='query_status' class='form-control query_status<?=$count1;?> ' style='width: 167px;'>
                         <?php
                         if($fetch_qr["client_status"]!='')
                         {
                         ?>
                         
                         <option value="<?=$fetch_qr["client_status"];?>"><?=$fetch_qr["client_status"];?></option>
                         
                         <?php
                         }
                         ?>

<option value="">Select</option>

<option value="Pipeline">Pipeline</option>
<option value="Visiting Completed">Visiting Completed</option>            
<option value="Under Projection">Under Projection</option>
<option value="Booking Completed">Booking Completed</option>
<option value="Collection Completed">Collection Completed</option>

<option value="Registration Completed">Registration Completed</option>
<option value="Expecting low budget">Expecting low budget</option>
<option value="Prefers Other location">Prefers Other location</option>
<option value="Future need">Future need</option>

</select>
<br>
<textarea name='query_status' class='form-control lead_remark<?=$count1;?> ' style='width: 167px;'><?=$fetch_qr['lead_remark'];?></textarea>
  
<br>
<button type="button" id='basicSuccessAnimation' class='btn btn-success query_statusubmit$i trigger'  onclick=submitapproval_call1('<?=$mainid;?>',this,<?=$count1;?>)  style='margin-top: 10%;'>submit</button>

<p hidden><?=$fetch_qr['lead_remark'];?></p>
    </div>
</div>
<br> 
<br>


</td>
<td ><?php echo $fetch_qr['remarks']; ?></td>

                            <td ><?php echo $fetch_qr['client_name']; ?></td>
                            <td ><?php echo $fetch_qr['client_number']; ?></td>
                             <td ><?php echo $fetch_qr['client_email']; ?></td>
                            <td ><?php echo $fetch_qr['client_location']; ?></td>
                           
                            <td ><?php echo $fetch_qr['client_job_type']; ?></td>
                            <td ><?php echo $fetch_qr['designation']; ?></td>
                            <td ><?php echo $fetch_qr['salary_per_month']; ?></td>
                           
                            <td ><?php echo $fetch_qr['property_type']; ?></td>
                            <td ><?php echo $fetch_qr['total_cents']; ?></td>
                            <td ><?php echo $fetch_qr['per_cent_budget']; ?></td>
                           
                            <td ><?php echo $fetch_qr['home_budget']; ?></td>
                             <td ><?php echo $fetch_qr['total_budget']; ?></td>
                             
                             <td ><?php echo $fetch_qr['lead_generated_by']; ?></td>
                             
                               <td ><?php echo $fetch_qr['assigned_to']; ?></td>
                             
                              <td ><?php echo $fetch_qr['telecaller']; ?></td>
                          
                          <td ><?php echo $fetch_qr['team_manager']; ?></td>
                       
                        
                <td><div class="d-flex">
                                                    
                             
  <?php echo can_edit("lead_list",$edit_acess,"new_lead.php?id=".$fetch_qr['id']."");?>
    
    
      <?php echo can_delete("lead_list",$delete_access,"delete_id.php?delete=".$fetch_qr['id']."&table=new_leads&page=lead_list");?>  
    
    
 

                 
                                                    
</div>
 </td>
 </tr>
<?php
$count1 = $count1+1;
}
}

}
 

    


  
$prabuinc++;
}
?>
                                    </tbody>
                                        </table>
                                     <button class="update-bulk" type="button" style="
    /* float: right; */
    padding: 5px;
    vertical-align: middle;
    margin-top: -23px;
" class="pagination btn btn-success" onclick="clickAllElements('trigger')">Update Bulk Status</button>
                                        
                                          <input type="text" name="staff" id="savewillpayvalue"    style='display:none'>
                                <button type="submit" name="save" id="savewillpay"  style='display:none'>submit</button>
                                
                                </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
  <script src="js/vendor/jquery-1.11.3.min.js"></script> 
<script src="js/bootstrap.min.js"></script> 
<script src="js/dropzone.js"></script>            
<script>
    $(document).ready(function () {
    getTemplates();
});


$(document).ready(function() {
        
            
               $("#filterTemplate").on("change", function () {
        updateTemplatePreview();
    });
            
        });

function toggleSection(section) {
    $(".form-container").removeClass("active");
    $("#" + section).addClass("active");
    $(".btn-option").removeClass("active");
    event.target.classList.add("active");
}


function updateTemplatePreview() {
    let selectedTemplate = $("#filterTemplate option:selected");
    let imgPath = selectedTemplate.attr("data-img");
    let folderPath = selectedTemplate.attr("data-folder");
    let filePath = selectedTemplate.attr("data-file"); // Get file name

    if (imgPath && folderPath) {
        let fullPath = folderPath + imgPath;
        $("#templatePreview").show();
        $("#templateImage").attr("src", fullPath).show();
        $("#attachments").val(filePath); // Store file name for attachment
    } else {
        $("#templatePreview").hide();
        $("#templateImage").attr("src", ""); // Clear image if no template is selected
        $("#attachments").val("");
    }
}

 function sendBulkMail() {
     
     let checkedEmails = [];

    $(".check-input:checked").each(function () {
        let email = $(this).closest("tr").find("td:eq(10)").text().trim(); // Extract email from the 4th column
        if (email) checkedEmails.push(email);
    });

    let additionalEmails = $('#to_email').val().trim();
    if (additionalEmails) {
        let manualEmails = additionalEmails.split(',').map(email => email.trim()); // Split and trim manually added emails
        checkedEmails = checkedEmails.concat(manualEmails); // Merge both lists
    }

    if (checkedEmails.length === 0) {
        alert("No email addresses found. Please check at least one client or enter an email manually.");
        return;
    }

    let toEmail = checkedEmails.join(", "); // Join emails with commas
    let ccEmail = $('#cc_email').val().trim();
    let bccEmail = $('#bcc_email').val().trim();
    let subject = $('#mail_subject').val().trim();
    let message = $('#summernote2').summernote('code');
    let attachments = $('#attachments').val(); // Attachment file name

    if (!toEmail) {
        alert("Recipient email is required.");
        return;
    }

    let formData = new FormData();
    formData.append("to_email", toEmail);
    formData.append("cc_email", ccEmail);
    formData.append("bcc_email", bccEmail);
    formData.append("mail_subject", subject);
    formData.append("mail_message", message);
    formData.append("attachments", attachments); // Attach the filename
 console.log("To Email:", toEmail);
    console.log("CC Email:", ccEmail);
    console.log("BCC Email:", bccEmail);
    console.log("Subject:", subject);
    console.log("Message:", message);
    console.log("Attachments:", attachments ? attachments.name : "No file attached");
    $.ajax({
        url: 'bulk_mail_client.php',
        type: 'POST',
        data: formData,
        processData: false, // Prevent automatic processing
        contentType: false, // Allow file attachments
        dataType: 'json',
        success: function (response) {
            if (response.status === 'success') {
                alert(response.message);
                location.reload();
            } else {
                alert(response.message);
            }
        },
        error: function () {
            alert("Error sending mail.");
        }
    });
}


       function uploadImage() {
        let fileInput = document.getElementById("image_upload");
        let file = fileInput.files[0];

        if (!file) {
            alert("Please select an image to upload.");
            return;
        }

        let formData = new FormData();
        formData.append("image", file);

        $.ajax({
            url: "upload_image.php",  // Update with your image hosting script or API
            type: "POST",
            data: formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function(response) {
                if (response.status === "success" && response.image_url) {
                    $("#image_url").val(response.image_url); // Store the image URL
                    sendWhatsAppMessage(response.image_url); // Pass URL to WhatsApp function
                } else {
                    alert("❌ Image upload failed. Try again.");
                }
            },
            error: function(xhr, status, error) {
                console.error("Image Upload Error:", xhr.responseText);
                alert("❌ Error uploading image. Check console for details.");
            }
        });
    }

    function sendWhatsAppMessage(imageUrl) {
        let checkedNumbers = [];

        $(".check-input:checked").each(function () {
            let phone = $(this).closest("tr").find("td:eq(9)").text().trim();
            if (phone) checkedNumbers.push(phone);
        });

        let manualNumber = $('#whatsapp_number').val().trim();
        if (manualNumber) checkedNumbers.push(manualNumber);

        if (checkedNumbers.length === 0) {
            alert("No phone numbers selected. Please check at least one or enter manually.");
            return;
        }

        let templateName = $('#template_name').val().trim();
        let templateLanguage = $('#template_language').val().trim();

        if (!templateName || !templateLanguage) {
            alert("Please enter a template name and language.");
            return;
        }

        let parameters = [];

        if (imageUrl) {
            parameters.push({
                "type": "image",
                "image": { "link": imageUrl }
            });
        }

        let formData = new FormData();
        formData.append("whatsapp_numbers", JSON.stringify([...new Set(checkedNumbers)]));
        formData.append("template_name", templateName);
        formData.append("template_language", templateLanguage);
        formData.append("template_parameters", JSON.stringify(parameters));

        console.log("Sending Data:", Object.fromEntries(formData.entries()));

        $.ajax({
            url: "send_whatsapp.php",
            type: "POST",
            data: formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function (response) {
                console.log("API Response:", response);

                if (!response || typeof response !== "object") {
                    alert("❌ Error: Invalid response format from server.");
                    console.error("Unexpected response:", response);
                    return;
                }

                if (response.status === "success" && response.responses.length > 0) {
                    let successCount = 0;
                    let messageDetails = response.responses.map((msg, index) => {
                        if (msg.status === "success") {
                            successCount++;
                            return `✅ #${index + 1} - Sent (ID: ${msg.message_id})`;
                        } else {
                            return `❌ #${index + 1} - Failed (${msg.reason})\nAPI Response: ${msg.api_response}`;
                        }
                    }).join("\n");

                    alert(`📨 ${successCount} WhatsApp Messages Sent Successfully!\n\nDetails:\n${messageDetails}`);
                } else {
                    alert("❌ Error: " + (response.message || "Unknown error"));
                    console.log("Debug Info:", response);
                }
            },
            error: function (xhr, status, error) {
                console.error("AJAX Error:", xhr.responseText);
                alert("❌ Error sending WhatsApp message. Check console for details.");
            }
        });
    }


function checkall(x)
   {
       var temp="";
       
       if(x.checked==true)
       {
          
           
           window.localStorage.setItem("temp",1);
           
           var len=document.getElementsByClassName("check-input").length;
           for(var i=0;i<len;i++)
           {
               var val=document.getElementsByClassName("check-input")[i].value;
              
               document.getElementsByClassName("check-input")[i].setAttribute("checked","true");
               document.getElementsByClassName("check-input")[i].checked=true;
           }
           
       }
       else
       {
         
           window.localStorage.setItem("temp",2);
           var len=document.getElementsByClassName("check-input").length;
           for(var i=0;i<len;i++)
           {
               document.getElementsByClassName("check-input")[i].setAttribute("checked","false");
                document.getElementsByClassName("check-input")[i].checked=false;
           }
           
          

           
       }
   }
   
function getTemplates() {
    $.ajax({
        url: "get_templatesapi.php", // Calls the PHP script
        type: "GET",
        dataType: "json",
        success: function (response) {
            console.log("API Response:", response);

            if (response.status === "success" && response.templates.length > 0) {
                let templateDropdown = $("#template_name");
                templateDropdown.empty().append('<option value="">Select a Template</option>');

                response.templates.forEach(template => {
                    templateDropdown.append(`<option value="${template.name}">${template.name}</option>`);
                });
            } else {
                alert("Error fetching templates: " + response.message);
            }
        },
        error: function (xhr, status, error) {
            console.error("Error fetching templates:", xhr.responseText);
            alert("❌ Error fetching templates. Check console for details.");
        }
    });
}

// Call function on page load


</script>           
                 <script>
function clickAllElements(className) {
    let elements = document.querySelectorAll(`.${className}`);
    // elements.forEach(element => element.click());
    console.log(elements.length);
}
    
    function setvalue(x)
    {
        document.getElementById("savewillpayvalue").value=x;
    }
    
    function trigfunction(x)
    {
        document.getElementById(x).click();
    }
        function checkall(x)
  {
       document.getElementsByClassName("btn-default")['0'].click();
      
      if(x.checked==true)
      {
          var len=document.getElementsByClassName("check-input").length;
          for(var i=0;i<len;i++)
          {
              document.getElementsByClassName("check-input")[i].setAttribute("checked","true");
              document.getElementsByClassName("check-input")[i].checked=true;
           
          }
         
      }
      else
      {
          var len=document.getElementsByClassName("check-input").length;
          for(var i=0;i<len;i++)
          {
              document.getElementsByClassName("check-input")[i].setAttribute("checked","false");
                document.getElementsByClassName("check-input")[i].checked=false;
                 
          }
      }
  }
       function submitapproval_call1(id,x,y)
  {
      
    
    
      var call_status=document.getElementsByClassName("call_status"+y)[0].value;
      var lead_status=document.getElementsByClassName("lead_status"+y)[0].value;
      var stu_calls=document.getElementsByClassName("query_status"+y)[0].value;
       var lead_remark=document.getElementsByClassName("lead_remark"+y)[0].value;
         var data2 = new FormData();
        
        data2.append("client_status",stu_calls);
        data2.append("call_status",call_status);
        data2.append("lead_status",lead_status);
       data2.append("lead_remark",lead_remark);

        data2.append("id",id);
        
     
     if(lead_status!="")
     {
         if(stu_calls!="")
         {
               x.innerHTML="Please Wait...";
const xhttp = new XMLHttpRequest();
  xhttp.onload = function() {
      alert(this.responseText);
   x.innerHTML = "Submitted";
    }
   
  xhttp.open("POST", "lead_status_update.php");
  xhttp.send(data2);
  
  
         }
     }
     else
     {
         alert("Please Fill All details");
     }
     
     



   
   
   
  }
  
   function submitapproval_call2(id,x,y)
  {
      
    
    
      var call_status=document.getElementsByClassName("call_status1"+y)[0].value;
      var lead_status=document.getElementsByClassName("lead_status1"+y)[0].value;
     
         var data2 = new FormData();
        
  
        data2.append("call_status",call_status);
        data2.append("lead_status",lead_status);
    

        data2.append("cons",id);
        
     
     if(call_status!="")
     {
         if(call_status=="Constructive")
         {
             
    x.innerHTML="Please Wait...";
const xhttp = new XMLHttpRequest();
  xhttp.onload = function() {
      alert(this.responseText);
   x.innerHTML = "Submitted";
    }
   
  xhttp.open("POST", "lead_status_update.php");
  xhttp.send(data2);
         }
         else if(call_status=="Non Constructive" && lead_status!='')
         {
             
               x.innerHTML="Please Wait...";
const xhttp = new XMLHttpRequest();
  xhttp.onload = function() {
      alert(this.responseText);
   x.innerHTML = "Submitted";
    }
   
  xhttp.open("POST", "lead_status_update.php");
  xhttp.send(data2);
         }
  
  
         
     }
     else
     {
         alert("Please Fill All details");
     }
     
     



   
   
   
  }
  
  
  
  
  function updateQueryStatus(leadStatus, queryStatusId) {
    var queryStatusDropdown = document.getElementsByClassName("query_status"+queryStatusId)[0];

    // Clear existing options
    queryStatusDropdown.innerHTML = "<option value=''>Select</option>";

    if (leadStatus === "Interested") {
        var options = [
            "Pipeline",
            "Visiting Completed",
            "Under Projection",
            "Booking Completed",
            "Collection Completed",
            "Registration Completed"
        ];
    } else if (leadStatus === "Not Interested") {
        var options = [
            "Expecting low budget",
            "Prefers Other location",
            "Future need"
        ];
    } else {
        var options = []; // Empty if no valid lead_status is selected
    }

    // Add new options dynamically
    options.forEach(function(optionText) {
        var option = document.createElement("option");
        option.value = optionText;
        option.textContent = optionText;
        queryStatusDropdown.appendChild(option);
    });
}


function updateQueryStatus1(leadStatus, queryStatusId) {
    var queryStatusDropdown = document.getElementsByClassName("lead_status1"+queryStatusId)[0];

    // Clear existing options
    queryStatusDropdown.innerHTML = "<option value=''>Select</option>";

    if (leadStatus === "Constructive") {
        var options = [];
    } else if (leadStatus === "Non Constructive") {
       
         var options = [
            "Not relevant",
            "No not available"
        ];
    } else {
        var options = []; // Empty if no valid lead_status is selected
    }

    // Add new options dynamically
    options.forEach(function(optionText) {
        var option = document.createElement("option");
        option.value = optionText;
        option.textContent = optionText;
        queryStatusDropdown.appendChild(option);
    });
}
document.addEventListener("DOMContentLoaded", function () {
    const observer = new MutationObserver((mutationsList, observer) => {
        for (let mutation of mutationsList) {
            if (mutation.type === "childList") {
                let paginationElement = document.querySelector(".fixed-table-pagination");
                let updateBulkElement = document.querySelector(".update-bulk");

                if (paginationElement && updateBulkElement) {
                    // Clone the element
                    let clonedElement = updateBulkElement.cloneNode(true);

                    // Check if the element is already inside paginationElement to prevent duplication
                    if (!paginationElement.contains(updateBulkElement)) {
                        // Insert as the first child
                        paginationElement.insertBefore(clonedElement, paginationElement.firstChild);

                        // Remove the original element
                        updateBulkElement.remove();
                    }

                    // Stop observing once the operation is completed
                    observer.disconnect();
                    break; // Exit the loop early since we've completed the task
                }
            }
        }
    });

    // Start observing the document body for changes
    observer.observe(document.body, { childList: true, subtree: true });
});



</script>
<?php
require('footer.php');
?>