<?php
session_start();
require('header.php');
include "dbconfig.php";
$link = opencon();
?>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <!-- Bootstrap (Required by Summernote) -->

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <!-- Summernote CSS & JS -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.18/summernote-lite.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.18/summernote-lite.min.js"></script>
<link rel="stylesheet" href="css/summernote.css" />
<style>
    .container-box {
        background: #f8f9fa;
        padding: 20px;
        border-radius: 8px;
        margin-bottom: 20px;
    }
    .title {
        font-size: 20px;
        font-weight: bold;
        color: #333;
        text-align: center;
        margin-bottom: 15px;
    }
    .btn-group {
        text-align: center;
        margin-bottom: 15px;
    }
    .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;
    }
</style>

<div class="container-fluid">
    <div class="row">
        <div class="col-lg-12">
            <div class="shadow-reset">

                <!-- Mail & WhatsApp Toggle -->
                <div class="btn-group">
                    <button class="btn-option active" onclick="toggleSection('mailForm')">Mail</button>
                    <button class="btn-option" onclick="toggleSection('whatsappForm')">WhatsApp</button>
                </div>

                <!-- Mail Form -->
                <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="summernote5" 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 Message</h4>
                    <form>
                        <div class="form-group">
                            <label>Recipient Number</label>
                            <input type="text" class="form-control" id="whatsapp_number" placeholder="Enter WhatsApp Number">
                        </div>
                        <div class="form-group">
                            <label>Message</label>
                            <textarea id="whatsappMessage" class="form-control" placeholder="Type your message here..."></textarea>
                        </div>
                        <button type="button" class="btn btn-success btn-block" onclick="sendWhatsAppMessage()">Send WhatsApp</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>

                <!-- Search Filters -->
                <form method="post">  
                <div class="container-box">
                    <h4 class="title">Search Clients</h4>
                     <div class="row">
                        
                         
                        <div class="col-md-4">
                            <label>Client Name</label>
                            <input type="text" id="filterName" class="form-control"  name="search_name" placeholder="Enter Client Name">
                        </div>
                        <div class="col-md-4">
                            <label>Area (Address)</label>
                            <input type="text" id="filterArea" class="form-control" name="search_area"  placeholder="Enter Area Name">
                        </div>
                    </div>
                    <div class="row mt-3">
                        <div class="col-md-12 text-center">
                            <button  type="submit" name="submit" class="btn btn-primary" >Search</button>
                        </div>
                    </div>
                </div>
</form>
                <!-- Client Table -->
                <div class="container-box">
                    <h4 class="title">Client List</h4>
                   <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>
                                        <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 onchange="checkall(this)" type='checkbox' id='checkAll'>Check All</th>
                                <th>Client Name</th>
                                <th>Phone</th>
                                <th>Email</th>
                                <th>Address</th>
                            </tr>
                        </thead>
                        <tbody id="clientTableBody">
                            <?php
                            $where1 = "WHERE id!=''";
                                    if (isset($_POST['submit'])) {
                                        if (!empty($_POST['project_name'])) {
                                            $where1 .= " AND project_name='" . $_POST['project_name'] . "'";
                                        }
                                        if (!empty($_POST['search_name'])) {
                                            $where1 .= " AND Name LIKE '%" . $_POST['search_name'] . "%'";
                                        }
                                        if (!empty($_POST['search_area'])) {
                                            $where1 .= " AND present_address LIKE '%" . $_POST['search_area'] . "%'";
                                        }
                                    }
                                    $sql = "SELECT * FROM new_client_details $where1";
                            $sql_exe = mysqli_query($link, $sql);
                            while ($fetch_qr = mysqli_fetch_array($sql_exe)) {
                                echo "<tr>"?> <td><input onclick="checkin(this)" class='check-input' type='checkbox' name='ids[]' value='<?php echo $fetch_qr['id'] ?>,<?php echo $fetch_qr['Phone1']?>,<?php echo $fetch_qr['Phone1'] ?>,Brochure - <?php echo $fetch_qr['Phone1'] ?>' ></td>
                               <?php    echo " <td>{$fetch_qr['Name']}</td>
                                    <td>{$fetch_qr['Phone1']}</td>
                                    <td>{$fetch_qr['Email']}</td>
                                    <td>{$fetch_qr['Curr_Location']}</td>
                                </tr>";
                            }
                            ?>
                        </tbody>
                    </table>
                </div>
 </div> </div>
            </div>
        </div>
    </div>
</div>

<!-- JavaScript -->
<script>



 $(document).ready(function() {
            $('#summernote5').summernote({
                height: 300,  // Editor height
                placeholder: 'Type your content here...',
                toolbar: [
                    ['style', ['bold', 'italic', 'underline', 'clear']],
                    ['para', ['ul', 'ol', 'paragraph']],
                    ['insert', ['link', 'picture', 'video']],
                    ['view', ['fullscreen', 'codeview', 'help']]
                ]
            });
            
               $("#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(2)").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 = $('#summernote5').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

    $.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 sendWhatsAppMessage() {
    alert("WhatsApp Message Sent!");
}

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

           
       }
   }
   


</script>

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