<style>
    .disabled-row {
        pointer-events: none;
    }

    .disabled-row td {
        background-color: #f8f9fa;
        color: #999;
        opacity: 0.6;
    }

    .dataTables_scrollHeadInner {
        width: 100% !important;
    }

    .dataTables_scrollHeadInner table {
        width: 100% !important;
    }

    /* .contact-dropdown-container {
        position: relative;
        max-width: 800px;
        margin: 0 auto;
    } */

    .contact-search-wrapper {
        position: relative;
        z-index: 2;
    }

    .contact-dropdown-list {
        position: absolute;
        z-index: 1;
        top: 3rem;
        width: 100%;
        border-radius: 10px;
        overflow: hidden;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        background: white;

        /* Initial hidden state */
        max-height: 0;
        opacity: 0;
        transform: translateY(-10px);

        /* Smooth transitions */
        transition: max-height 0.4s cubic-bezier(0.4, 0, 0.2, 1),
            opacity 0.3s ease-in-out,
            transform 0.3s ease-in-out,
            box-shadow 0.3s ease-in-out;
    }

    .contact-dropdown-list.dropdown-visible {
        max-height: 500px;
        /* Adjust based on your content height */
        opacity: 1;
        transform: translateY(0);
    }

    /* Enhanced search input styling */
    .contact-search-input {
        transition: all 0.3s ease-in-out;
        border: 2px solid #e9ecef;
    }

    .contact-search-input:focus {
        border-color: #556b2f;
        box-shadow: 0 0 0 0.2rem rgba(85, 107, 47, 0.25);
    }

    /* Table styling improvements */
    .contact-table th {
        background-color: #f8f9fa;
        font-weight: 600;
        padding: 12px 15px;
    }

    .contact-table td {
        padding: 12px 15px;
        vertical-align: middle;
    }

    .contact-table tbody tr:hover {
        background-color: #f8f9fa;
    }

    /* Button hover effects */
    .contact-filter-btn {
        transition: all 0.2s ease-in-out;
    }

    .contact-filter-btn:hover {
        background-color: #4a5d2a;
        transform: translateY(-1px);
    }

    /* Custom scrollbar for the dropdown */
    .contact-table-wrapper {
        max-height: 400px;
        overflow-y: auto;
        overflow-x: hidden;
    }

    .contact-search-icon {
        cursor: pointer;
    }

    /* Animation delay for table rows */
    .contact-dropdown-list.dropdown-visible .contact-table tbody tr {
        animation: slideInContactRow 0.3s ease-out forwards;
        opacity: 0;
        transform: translateX(-20px);
    }

    .contact-dropdown-list.dropdown-visible .contact-table tbody tr:nth-child(1) {
        animation-delay: 0.1s;
    }

    .contact-dropdown-list.dropdown-visible .contact-table tbody tr:nth-child(2) {
        animation-delay: 0.15s;
    }

    .contact-dropdown-list.dropdown-visible .contact-table tbody tr:nth-child(3) {
        animation-delay: 0.2s;
    }

    .contact-dropdown-list.dropdown-visible .contact-table tbody tr:nth-child(4) {
        animation-delay: 0.25s;
    }

    .contact-dropdown-list.dropdown-visible .contact-table tbody tr:nth-child(5) {
        animation-delay: 0.3s;
    }

    @keyframes slideInContactRow {
        to {
            opacity: 1;
            transform: translateX(0);
        }
    }


    .btn-custom {
        background-color: transparent;
        color: #28a745;
        border: 2px solid #28a745;
        transition: background-color 0.3s, color 0.3s;
        width: 150px;
        /* Adjust width as needed */
        padding: 10px;
    }

    .btn-custom:hover {
        background-color: #28a745;
        color: white;
    }

    .deleteContact:hover svg {
        fill: white;
        transition: fill 0.3s ease-in-out;
    }

    .deleteContact {
        fill: #F44336;
    }

    #toggleBroadcast svg {
        cursor: pointer;
    }

    #selectAll {
        transform: scale(1.4);
    }

    .invalid-contacts-banner {
        border: 2px solid #f6cf01;
        border-radius: 8px;
        padding: 0.5rem 1rem;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #f6cf0114;
    }

    .invalid-contacts-banner button {
        background-color: #f5fff6;
    }

    .invalid-contacts-banner button:hover {
        background-color: #287F71;
    }

    #accordionExample {
        background-color: #F6F8FB;
    }

    #contacts-main {
        background-color: #F6F8FB;
        padding: 1rem 1.2rem;
        padding-top: 1px;
        margin-top: 2rem;
        border-radius: 10px;
    }

    #contactSearchInput {
        border: 1px solid #dee2e6;
    }

    #all_contacts_table {
        border-bottom: 1px solid lightgrey;
        margin-bottom: 1rem !important;
    }
</style>

<div class="content" id="createBroadcast">

    <!-- Start Content-->
    <div class="container-fluid d-none" id="anotherSection">
        <div class="pt-3 pb-2 d-flex align-items-sm-center flex-sm-row flex-column">
            <div class="flex-grow-1" id="toggleBroadcast">
                <h4 class="fs-18 fw-semibold m-0">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" style="fill: rgba(0, 0, 0, 1);">
                        <path d="M12.707 17.293 8.414 13H18v-2H8.414l4.293-4.293-1.414-1.414L4.586 12l6.707 6.707z"></path>
                    </svg>
                    New Broadcast
                </h4>
            </div>
            <div>
                <button class="btn btn-outline-success me-2 new-broadcast-btn">Add Broadcast</button>
                <button class="btn btn-danger me-2">Discard</button>

            </div>

        </div>
        <div class="pb-2">
            <div class="row">
                <div class="col-xl-9 newTemplateForm">
                    <div class="card overflow-hidden">

                        <!-- <div class="card-header">
                                    <div class="d-flex align-items-center">
                                        <h5 class="card-title mb-0">All Templates</h5>
                                    </div>
                                </div> -->

                        <div class="card-body mt-0">
                            <div style="background-color: white;" class="rounded-2 px-1 my-2 py-2">
                                <p class="m-0 fw-bold">What message do you want to send?</p>
                                <p class="m-0">Add broadcast name and template below</p>
                            </div>
                            <form action="" id="broadcast_form">
                                <div>
                                    <div>
                                        <div class="mb-3">
                                            <label for="simpleinput" class="form-label fw-bold">Broadcast Name</label>
                                            <input type="text" id="simpleinput" name="broadcast_name" class="form-control inputbgcolor" placeholder="Broadcast Name">
                                        </div>
                                    </div>
                                    <div>
                                        <div class="mb-3">
                                            <div class="d-flex justify-content-between">
                                                <div><label for="simpleinput" class="form-label fw-bold">Select template message</label></div>
                                                <div>
                                                    <a href="https://app.watify.io/my-templates?my-template=yes">+Add new template</a>
                                                </div>
                                            </div>
                                            <select class="form-select inputbgcolor" name="template_category" id="templateCategory">
                                                <option value="">Select Category</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div>
                                        <div class="d-flex justify-content-between">
                                            <div>
                                                <h6 class="mb-1">Who do you want to send it to ?</h6>
                                                <p>
                                                    Select contacts below or
                                                    <a href="#" onclick="downloadFile()">Download sample format for contact upload</a>
                                                </p>
                                            </div>
                                            <div>
                                                <button class="btn btn-outline-success me-2">Import contacts</button>
                                            </div>
                                        </div>
                                        <!-- accordian start -->
                                        <div class="accordion exclude-div d-none" id="accordionExample">
                                            <div class="accordion-item">
                                                <h2 class="accordion-header" id="headingOne">
                                                    <button class="accordion-button fw-medium" style="box-shadow: unset; background-color: #F6F8FB; font-weight:bold;" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
                                                        Exclude invalid contacts
                                                        <span class="mdi mdi-help-circle" style="color: grey; font-size:0.9rem; margin-left:5px;"></span>
                                                    </button>
                                                </h2>
                                                <div id="collapseOne" class="accordion-collapse collapse" aria-labelledby="headingOne" data-bs-parent="#accordionExample">
                                                    <div class="accordion-body">
                                                        <!-- <strong>This is the first item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow. -->
                                                        <div>
                                                            <div class="d-flex gap-2 align-items-center">
                                                                <input type="checkbox" style="transform: scale(1.4); cursor: pointer;">
                                                                <span>Exclude <span class="invalid-contacts">4476</span> invalid contacts from this broadcast</span>
                                                            </div>
                                                            <div class="d-flex gap-2 align-items-center mt-2">
                                                                <input type="checkbox" style="transform: scale(1.4); cursor: pointer;">
                                                                <span>Always exclude invalid contacts from broadcast</span>
                                                            </div>
                                                        </div>
                                                        <div class="mt-4 invalid-contacts-banner">
                                                            <span class="mdi mdi-alert-circle-outline fs-4" style="color: #f6cf01;"></span>
                                                            <span style="font-weight: bold;"> Would you like to delete <span class="invalid-contacts">4476</span> invalid contacts from your contacts list?</span>
                                                            <button class="btn btn-outline-success me-2" id="delete-invalid-contacts">Yes, delete</button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <!-- <div id="main-contant">
                                            <div class="d-flex align-items-center my-4">
                                                <div class="input-group" style="width: 500px;">
                                                    <input type="text" class="form-control" placeholder="Search...">
                                                    <span class="input-group-text">
                                                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"
                                                            style="fill: rgba(13, 13, 13, 0.62);">
                                                            <path
                                                                d="M10 18a7.952 7.952 0 0 0 4.897-1.688l4.396 4.396 1.414-1.414-4.396-4.396A7.952 7.952 0 0 0 18 10c0-4.411-3.589-8-8-8s-8 3.589-8 8 3.589 8 8 8zm0-14c3.309 0 6 2.691 6 6s-2.691 6-6 6-6-2.691-6-6 2.691-6 6-6z">
                                                            </path>
                                                        </svg>
                                                    </span>
                                                </div>
                                                <button class="btn btn-success rounded-1 border-0 d-flex align-items-center justify-content-center"
                                                    style="padding: 8px 12px; margin-left: 5px;">
                                                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"
                                                        style="fill: rgb(255, 255, 255);">
                                                        <path
                                                            d="M21 3H5a1 1 0 0 0-1 1v2.59c0 .523.213 1.037.583 1.407L10 13.414V21a1.001 1.001 0 0 0 1.447.895l4-2c.339-.17.553-.516.553-.895v-5.586l5.417-5.417c.37-.37.583-.884.583-1.407V4a1 1 0 0 0-1-1zm-6.707 9.293A.996.996 0 0 0 14 13v5.382l-2 1V13a.996.996 0 0 0-.293-.707L6 6.59V5h14.001l.002 1.583-5.71 5.71z">
                                                        </path>
                                                    </svg>
                                                </button>
                                            </div>

                                            <div class="row contact-list">
                                                <div class="col-xl-12" style="padding: 0;">
                                                    <div class="card overflow-hidden" style="margin-bottom: 0px;">

                                                        <div class="card-body mt-0">
                                                            <div class="table-responsive table-card mt-0" id="all_contacts_div">
                                                                <table id="all_contacts" class="table table-borderless table-centered align-middle " style="width: 100%;">
                                                                    <thead class="text-muted table-light">
                                                                        <tr>
                                                                            <th scope="col" class="cursor-pointer"><input type="checkbox" class="" name="" id=""></th>
                                                                            <th scope="col" class="cursor-pointer">Name</th>
                                                                            <th scope="col" class="cursor-pointer">Phone</th>
                                                                            <th scope="col" class="cursor-pointer text-center">Allow Broadcast</th>
                                                                        </tr>
                                                                    </thead>
                                                                    <tbody>

                                                                    </tbody>
                                                                </table>
                                                            </div>
                                                        </div>

                                                    </div>
                                                </div>

                                            </div>
                                        </div> -->




                                        <!-- <div class="d-none" id="filter-options">
                                            <div id="filters-con">
                                            </div>
                                            <div class="mb-2">
                                                <button type="button" class="btn btn-outline-success me-2 add-new-filter-btn">Add another filter</button>
                                            </div>
                                        </div> -->


                                    </div>
                                </div>
                                <div id="contacts-main">
                                    <div>
                                        <div class="contact-dropdown-container">
                                            <div class="contact-search-wrapper">
                                                <div class="d-flex align-items-center my-4">
                                                    <div class="input-group" style="width: 500px;">
                                                        <input type="text" id="contactSearchInput" class="form-control contact-search-input" placeholder="Search contacts...">
                                                        <span class="input-group-text" id="contact-search-icon">
                                                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"
                                                                style="fill: rgba(13, 13, 13, 0.62);">
                                                                <path
                                                                    d="M10 18a7.952 7.952 0 0 0 4.897-1.688l4.396 4.396 1.414-1.414-4.396-4.396A7.952 7.952 0 0 0 18 10c0-4.411-3.589-8-8-8s-8 3.589-8 8 3.589 8 8 8zm0-14c3.309 0 6 2.691 6 6s-2.691 6-6 6-6-2.691-6-6 2.691-6 6-6z">
                                                                </path>
                                                            </svg>
                                                        </span>
                                                    </div>
                                                    <button id="filter-btn" type="button" class="btn btn-success contact-filter-btn rounded-1 border-0 d-flex align-items-center justify-content-center"
                                                        style="padding: 8px 12px; margin-left: 5px;">
                                                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"
                                                            style="fill: rgb(255, 255, 255);">
                                                            <path
                                                                d="M21 3H5a1 1 0 0 0-1 1v2.59c0 .523.213 1.037.583 1.407L10 13.414V21a1.001 1.001 0 0 0 1.447.895l4-2c.339-.17.553-.516.553-.895v-5.586l5.417-5.417c.37-.37.583-.884.583-1.407V4a1 1 0 0 0-1-1zm-6.707 9.293A.996.996 0 0 0 14 13v5.382l-2 1V13a.996.996 0 0 0-.293-.707L6 6.59V5h14.001l.002 1.583-5.71 5.71z">
                                                            </path>
                                                        </svg>
                                                    </button>
                                                </div>
                                            </div>

                                            <!-- Available contacts -->
                                            <!-- <div class="row contact-dropdown-list" id="all_contacts">
                                                    <div class="col-xl-12" style="padding: 0;">
                                                        <div class="card overflow-hidden" style="margin-bottom: 0px;">
                                                            <div class="card-body mt-0">
                                                                <div class="contact-table-wrapper table-card mt-0">
                                                                    <table id="all_contacts_table" class="contact-table table table-borderless table-centered align-middle" style="width: 100%;">
                                                                        <thead class="text-muted table-light">
                                                                            <tr>
                                                                                <th scope="col" class="cursor-pointer">
                                                                                </th>
                                                                                <th scope="col" class="cursor-pointer">Name</th>
                                                                                <th scope="col" class="cursor-pointer">Phone</th>
                                                                                <th scope="col" class="cursor-pointer">Allow Broadcast</th>
                                                                            </tr>
                                                                        </thead>
                                                                        <tbody></tbody>
                                                                    </table>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div> -->
                                        </div>
                                        <div class="container mb-2 d-none" id="filter-options">
                                            <div id="filters-con">
                                            </div>
                                            <button class="btn btn-custom mt-2 new-filter-btn" onclick="addNewRow()">Add +</button>
                                        </div>
                                    </div>
                                    <div>
                                        <div class="d-flex justify-content-between">
                                            <div>
                                                <!-- 94805 -->
                                                <p><strong>Selected:</strong> <span style="color:green">0/<span id="max-contant">0</span> contacts remaining</span></p>
                                            </div>
                                            <div>
                                                <p class="fw-bold">current limits: 100000 unique contacts/24hours</p>
                                            </div>
                                        </div>
                                        <div class="progress mt-2" style="background-color: rgba(0, 0, 0, 0.1);">
                                            <div class="progress-bar bg-success" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
                                                0%
                                            </div>
                                        </div>
                                    </div>
                                    <hr />
                                    <!-- table start -->
                                    <div class="mt-4" id="contacts_table_main">
                                        <table id="all_contacts_table" class="table table-bordered">
                                            <thead class="table-light">
                                                <tr>
                                                    <th><input type="checkbox" id="selectAll"></th>
                                                    <th>Name</th>
                                                    <th>Phone</th>
                                                    <th style="text-align: center;">Allow Broadcast</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                                <div class="d-flex justify-content-between mt-5">
                                    <div>
                                        <div class="d-flex align-items-center">
                                            <h4 class="m-0">Enable ROI Tracking</h4>
                                            <div class="d-flex align-items-center rounded-3 ms-2 py-0 px-2" style="background-color: #ff69b4; width: fit-content; height: 20px;">
                                                <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" style="fill: #ffffff;">
                                                    <path d="M11.219 3.375 8 7.399 4.781 3.375A1.002 1.002 0 0 0 3 4v15c0 1.103.897 2 2 2h14c1.103 0 2-.897 2-2V4a1.002 1.002 0 0 0-1.781-.625L16 7.399l-3.219-4.024c-.381-.474-1.181-.474-1.562 0zM5 19v-2h14.001v2H5zm10.219-9.375c.381.475 1.182.475 1.563 0L19 6.851 19.001 15H5V6.851l2.219 2.774c.381.475 1.182.475 1.563 0L12 5.601l3.219 4.024z"></path>
                                                </svg>
                                                <span class="ms-1 text-white fw-semibold" style="font-size: 12px;">Business Feature</span>
                                            </div>
                                        </div>
                                        <p>Enable this feature to uncover user engagement, track conversion and optimize your broadcast</p>
                                    </div>
                                    <div>
                                        <button class="btn btn-success d-flex align-items-center text-white fw-bold rounded-3 px-2 py-1 border-0"
                                            style="margin:5px">
                                            Upgrade
                                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"
                                                style="fill: rgb(255, 255, 255); margin-left: 5px;">
                                                <path d="M5 20h14v-2H5v2zm7-18l-6 6h4v6h4v-6h4l-6-6z"></path>
                                            </svg>
                                        </button>
                                    </div>
                                </div>
                                <div class="p-3 border rounded my-2">
                                    <h6 class="fw-semibold">When do you want to send it?</h6>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="sendOption" value="send_now" id="sendNow" checked>
                                        <label class="form-check-label" for="sendNow">
                                            Send Now
                                        </label>
                                    </div>
                                    <div class="form-check mt-2">
                                        <input class="form-check-input" type="radio" name="sendOption" value="send_schedule" id="scheduleTime">
                                        <label class="form-check-label" for="scheduleTime">
                                            Schedule for Specific Time
                                        </label>
                                    </div>

                                    <!-- Hidden Date & Time Section -->
                                    <div id="dateTimeSection" class="mt-3 d-none">
                                        <div class="row g-2">
                                            <div class="col-md-6">
                                                <label for="scheduleDate" class="form-label fw-semibold">Select Date</label>
                                                <input type="date" name="schedule_date" class="form-control" id="scheduleDate">
                                            </div>
                                            <div class="col-md-6">
                                                <label for="scheduleTimeInput" class="form-label fw-semibold">Select Time</label>
                                                <input type="time" name="schedule_time" class="form-control" id="scheduleTimeInput">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                <div class="col-xl-3">
                    <div class="d-flex flex-column align-items-center">
                        <div class="mt-3">
                            <h5 class="text-center">Preview</h5>
                        </div>
                        <div style="background-image: url(https://live.wati.io/assets/preview_phone_bg-DgrnAayw.png);background-repeat: no-repeat;background-position: center center;background-size: contain;width: 306px;height: 570px;">
                            <div class="preview-message" style="max-height: 416px;overflow: auto;margin: 87px 20px 0px 18px;padding-bottom: 20px;">
                                <div class="preview-message-container">
                                    <div id="broadcast-title-container">

                                    </div>

                                    <div class="text-dark" id="preview-message-body-text"></div>

                                    <div class="d-flex justify-content-between align-items-end" style="font-size: 12px;">
                                        <div id="preview-message-footer-text" style="max-width: 200px;overflow: hidden;direction: initial;text-align: initial;font-size:12px;"></div>
                                        <div class="fs-smaller">12:12</div>
                                    </div>

                                    <div class="text-dark" id="preview-message-footer-links-container">
                                        <div id="preview-visit-website-container"></div>
                                        <div id="copy-button-preview-container"></div>
                                        <div id="quick-reply-button-preview-container"></div>
                                        <!-- <div class="preview-message-footer my-2 link d-flex gap-2 align-items-center justify-content-center" style="cursor: pointer;">
                                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="14" height="14" color="#276afd" fill="none">
                                                        <path d="M11.0991 3.00012C7.45013 3.00669 5.53932 3.09629 4.31817 4.31764C3.00034 5.63568 3.00034 7.75704 3.00034 11.9997C3.00034 16.2424 3.00034 18.3638 4.31817 19.6818C5.63599 20.9999 7.75701 20.9999 11.9991 20.9999C16.241 20.9999 18.3621 20.9999 19.6799 19.6818C20.901 18.4605 20.9906 16.5493 20.9972 12.8998" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
                                                        <path d="M20.556 3.49612L11.0487 13.0586M20.556 3.49612C20.062 3.00151 16.7343 3.04761 16.0308 3.05762M20.556 3.49612C21.05 3.99074 21.0039 7.32273 20.9939 8.02714" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
                                                    </svg>
                                                    <span class="" style="font-size: 0.8rem; color: #276afd;">Visit</span>
                                                </div> -->
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div> <!-- container-fluid -->
</div> <!-- content -->
<script>
    let allFilters = [];
    let contact_attributes = [];

    const callIcon = `
    <svg viewBox="0 0 24 24" width="14" fill="none" xmlns="http://www.w3.org/2000/svg">
        <g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path d="M3 5.5C3 14.0604 9.93959 21 18.5 21C18.8862 21 19.2691 20.9859 19.6483 20.9581C20.0834 20.9262 20.3009 20.9103 20.499 20.7963C20.663 20.7019 20.8185 20.5345 20.9007 20.364C21 20.1582 21 19.9181 21 19.438V16.6207C21 16.2169 21 16.015 20.9335 15.842C20.8749 15.6891 20.7795 15.553 20.6559 15.4456C20.516 15.324 20.3262 15.255 19.9468 15.117L16.74 13.9509C16.2985 13.7904 16.0777 13.7101 15.8683 13.7237C15.6836 13.7357 15.5059 13.7988 15.3549 13.9058C15.1837 14.0271 15.0629 14.2285 14.8212 14.6314L14 16C11.3501 14.7999 9.2019 12.6489 8 10L9.36863 9.17882C9.77145 8.93713 9.97286 8.81628 10.0942 8.64506C10.2012 8.49408 10.2643 8.31637 10.2763 8.1317C10.2899 7.92227 10.2096 7.70153 10.0491 7.26005L8.88299 4.05321C8.745 3.67376 8.67601 3.48403 8.55442 3.3441C8.44701 3.22049 8.31089 3.12515 8.15802 3.06645C7.98496 3 7.78308 3 7.37932 3H4.56201C4.08188 3 3.84181 3 3.63598 3.09925C3.4655 3.18146 3.29814 3.33701 3.2037 3.50103C3.08968 3.69907 3.07375 3.91662 3.04189 4.35173C3.01413 4.73086 3 5.11378 3 5.5Z" stroke="#276afd" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></g>
    </svg>
    `;

    const redirectIcon = `
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="14" height="14" color="#276afd" fill="none">
                <path d="M11.0991 3.00012C7.45013 3.00669 5.53932 3.09629 4.31817 4.31764C3.00034 5.63568 3.00034 7.75704 3.00034 11.9997C3.00034 16.2424 3.00034 18.3638 4.31817 19.6818C5.63599 20.9999 7.75701 20.9999 11.9991 20.9999C16.241 20.9999 18.3621 20.9999 19.6799 19.6818C20.901 18.4605 20.9906 16.5493 20.9972 12.8998" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
                <path d="M20.556 3.49612L11.0487 13.0586M20.556 3.49612C20.062 3.00151 16.7343 3.04761 16.0308 3.05762M20.556 3.49612C21.05 3.99074 21.0039 7.32273 20.9939 8.02714" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
            </svg>
        `;

    const copyIcon = `
            <svg viewBox="0 0 24 24" width="14" fill="none" xmlns="http://www.w3.org/2000/svg">
                <g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path fill-rule="evenodd" clip-rule="evenodd" d="M15 1.25H10.9436C9.10583 1.24998 7.65019 1.24997 6.51098 1.40314C5.33856 1.56076 4.38961 1.89288 3.64124 2.64124C2.89288 3.38961 2.56076 4.33856 2.40314 5.51098C2.24997 6.65019 2.24998 8.10582 2.25 9.94357V16C2.25 17.8722 3.62205 19.424 5.41551 19.7047C5.55348 20.4687 5.81753 21.1208 6.34835 21.6517C6.95027 22.2536 7.70814 22.5125 8.60825 22.6335C9.47522 22.75 10.5775 22.75 11.9451 22.75H15.0549C16.4225 22.75 17.5248 22.75 18.3918 22.6335C19.2919 22.5125 20.0497 22.2536 20.6517 21.6517C21.2536 21.0497 21.5125 20.2919 21.6335 19.3918C21.75 18.5248 21.75 17.4225 21.75 16.0549V10.9451C21.75 9.57754 21.75 8.47522 21.6335 7.60825C21.5125 6.70814 21.2536 5.95027 20.6517 5.34835C20.1208 4.81753 19.4687 4.55348 18.7047 4.41551C18.424 2.62205 16.8722 1.25 15 1.25ZM17.1293 4.27117C16.8265 3.38623 15.9876 2.75 15 2.75H11C9.09318 2.75 7.73851 2.75159 6.71085 2.88976C5.70476 3.02502 5.12511 3.27869 4.7019 3.7019C4.27869 4.12511 4.02502 4.70476 3.88976 5.71085C3.75159 6.73851 3.75 8.09318 3.75 10V16C3.75 16.9876 4.38624 17.8265 5.27117 18.1293C5.24998 17.5194 5.24999 16.8297 5.25 16.0549V10.9451C5.24998 9.57754 5.24996 8.47522 5.36652 7.60825C5.48754 6.70814 5.74643 5.95027 6.34835 5.34835C6.95027 4.74643 7.70814 4.48754 8.60825 4.36652C9.47522 4.24996 10.5775 4.24998 11.9451 4.25H15.0549C15.8297 4.24999 16.5194 4.24998 17.1293 4.27117ZM7.40901 6.40901C7.68577 6.13225 8.07435 5.9518 8.80812 5.85315C9.56347 5.75159 10.5646 5.75 12 5.75H15C16.4354 5.75 17.4365 5.75159 18.1919 5.85315C18.9257 5.9518 19.3142 6.13225 19.591 6.40901C19.8678 6.68577 20.0482 7.07435 20.1469 7.80812C20.2484 8.56347 20.25 9.56458 20.25 11V16C20.25 17.4354 20.2484 18.4365 20.1469 19.1919C20.0482 19.9257 19.8678 20.3142 19.591 20.591C19.3142 20.8678 18.9257 21.0482 18.1919 21.1469C17.4365 21.2484 16.4354 21.25 15 21.25H12C10.5646 21.25 9.56347 21.2484 8.80812 21.1469C8.07435 21.0482 7.68577 20.8678 7.40901 20.591C7.13225 20.3142 6.9518 19.9257 6.85315 19.1919C6.75159 18.4365 6.75 17.4354 6.75 16V11C6.75 9.56458 6.75159 8.56347 6.85315 7.80812C6.9518 7.07435 7.13225 6.68577 7.40901 6.40901Z" fill="#276afd"></path> </g>
            </svg>
        `;

    const replyIcon = `
            <svg fill="#276afd" width="14" viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">
                <g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <title>reply</title> <path d="M3.488 15.136q0 0.96 0.8 1.472l10.72 7.136q0.416 0.288 0.896 0.32t0.928-0.224 0.704-0.672 0.256-0.896v-3.584q3.456 0 6.208 1.984t3.872 5.152q0.64-1.792 0.64-3.552 0-2.912-1.44-5.376t-3.904-3.904-5.376-1.44v-3.584q0-0.48-0.256-0.896t-0.704-0.672-0.928-0.224-0.896 0.32l-10.72 7.136q-0.8 0.512-0.8 1.504z"></path> </g>
            </svg>
        `;
</script>

<script>
    function getPreviewContent(id, defaultPreviewContent, type, text) {
        let object = {};

        if (type === "url") {
            object["icon"] = redirectIcon;
            object["text"] = "Visit";
            object["className"] = "addWebsiteButtonText";

        } else if (type === "phone") {
            object["icon"] = btncallIcon;
            object["text"] = "Call";
            object["className"] = "addWebsiteButtonText";

        } else if (type === "copy") {
            object["icon"] = copyIcon;
            object["text"] = "Copy offer code";
            object["className"] = "copyButtonText";

        } else if (type === "quickReply") {
            object["icon"] = replyIcon;
            object["text"] = "Quick reply";
            object["className"] = "quickReplyButtonText";
        }

        return `
            <div preview-data="${defaultPreviewContent}">
                <div id="${id}" class="preview-message-footer my-2 link d-flex gap-2 align-items-center justify-content-center" style="cursor: pointer;">
                    ${object.icon}
                    <span class="${object.className}" style="font-size: 0.8rem; color: #276afd;">${text??object.text}</span>
                </div>
            </div>
        `
    }

    const columns = [{
            data: 'id',
            orderable: false,
            width: '10%'
        }, // For checkbox or action
        {
            data: 'name',
            width: '30%'
        },
        {
            data: 'phone',
            width: '40%'
        },
        {
            data: 'Allow Broadcast',
            orderable: false,
            width: '20%'
        }
    ];
    // Function to load datatable
    function loadTable(columnIndex = 1, where = null, extrawhere = null, sort_by_createdAt = false) {

        let dataTableInstance = $('#all_contacts_table').DataTable({
            autoWidth: false, // Disable auto width
            deferRender: true,
            processing: true,
            scrollX: true, // Enable horizontal scroll
            serverSide: true,
            stateSave: false,
            destroy: true, // Ensure proper cleanup before re-initializing
            ajax: {
                url: 'server/fetch_template?client_contacts=1',
                type: "GET",
                data: {
                    all_leads_where_clause: where,
                    extrawhere: extrawhere,
                    sort_by_createdAt,
                    // Send filters as JSON string
                    filters: JSON.stringify(allFilters || [])
                },
                // dataSrc: function(json) {
                // This is where you can see the debug info
                // if (json.debug && json.query_info) {
                //     console.log('=== SQL DEBUG INFO ===');
                //     console.log('Table Structure:', json.query_info.table);
                //     console.log('Base WHERE:', json.query_info.baseWhereCondition);
                //     console.log('Filter JOINs:', json.query_info.filterJoins);
                //     console.log('Filter CONDITIONS:', json.query_info.filterWhereConditions);
                //     console.log('Final Query:', json.query_info.final_query);
                //     console.log('=====================');
                // }
                // Return the data for DataTables to process
                // return json.data
                // }
            },
            columns: columns,
            colReorder: true,
            fixedHeader: {
                header: true,
                headerOffset: 0
            },
            keys: true,
            responsive: false,
            pageLength: 10,
            searching: false,
            drawCallback: function(settings) {
                // console.log(settings.json.query);
                const contactTable = document.getElementById('all_contacts_table');
                const contactRows = contactTable.querySelectorAll('tbody tr');

                contactRows.forEach(row => {
                    const contactAttri = row.cells[3]; // update index if needed
                    const contactAttriVal = contactAttri?.textContent?.toLowerCase()?.trim();

                    if (contactAttri && contactAttriVal) {
                        contactAttri.style.textAlign = 'center';

                        if (contactAttriVal === "false") {
                            row.classList.add('disabled-row');
                        }
                    }
                });
            },

        });

        // Force column width adjustment after rendering
        dataTableInstance.on('init', function() {
            setTimeout(function() {
                dataTableInstance.columns.adjust();
                if (columnIndex != -1) {
                    dataTableInstance.order([columnIndex, 'desc']);
                }
                // dataTableInstance.draw();
            }, 500);
        });

        return dataTableInstance;
    }

    // Function to apply filters and reload table
    function applyFilters() {
        const searchVal = contactSearchInput.value.trim().toLowerCase(); // Trim & lowercase for safety
        if (searchVal === '') {
            return;
        }
        console.log(allFilters);
        let query = `(name LIKE '%${searchVal}%' or phone LIKE '%${searchVal}%')`;

        loadTable(1, query); // Load table with filters
    }



    function addNewRow() {
        const filtersCon = document.getElementById("filters-con");
        const newRowHTML = `
        <div class="d-flex align-items-center gap-2 mt-2 filter-row">
            <div class="form-group" style="width: 300px;">
                <select class="form-select attribute-names-select">
                <option value="" disabled selected>Select an attribute</option>
                </select>
            </div>

            <div class="form-group" style="width: 300px;">
                <select class="form-select operation-select">
                <option value="" disabled selected>Operation</option>
                                    <option value="contains">Contains</option>
                                    <option value="does not contain">Does not contain</option>
                                    <option value="exists">Exists</option>
                                    <option value="does not exist">Does not exist</option>
                                    <option value="=">Equal</option>
                                    <option value="!=">Doesn't Equal</option>
                                    <option value=">">Greater Than</option>
                                    <option value="<">Less Than</option>
                                    <option value=">=">Greater Than or Equal To</option>
                                    <option value="<=">Less Than or Equal To</option>
                </select>
            </div>
            <div class="form-group" style="width: 300px;">
                <select class="form-select searchable_dropdown attribute-values-select">
                    <option value="" disabled selected>Select a value</option>
                </select>
            </div>

            <button class="btn btn-outline-danger deleteContact">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                    <path d="M5 20a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8h2V6h-4V4a2 2 0 0 0-2-2H9a2 2 0 0 0-2 2v2H3v2h2zM9 4h6v2H9zM8 8h9v12H7V8z"></path>
                    <path d="M9 10h2v8H9zm4 0h2v8h-2z"></path>
                </svg>
            </button>
        </div>`;

        filtersCon.insertAdjacentHTML("beforeend", newRowHTML); // appended new rows 

        let newRow = filtersCon.lastElementChild;
        let filter = {
            index: Date.now(),
            attribute_name: '',
            operation: '',
            attribute_value: ''
        };
        // Get only the new dropdown
        let newAttributeDropdown = newRow.querySelector(".attribute-names-select");
        let newOperationDropdown = newRow.querySelector(".operation-select");
        let newAttributeValDropdown = newRow.querySelector(".attribute-values-select");
        const addNewRowBtn = document.querySelector('.btn-custom');

        newAttributeValDropdown.disabled = true; // Disable initially
        addNewRowBtn.disabled = true;

        contact_attributes.forEach(function(attri) {
            if (!allFilters.some(f => f.attribute_name === attri.attribute_name)) {
                const option = document.createElement("option");
                option.value = attri.attribute_name;
                option.textContent = attri.attribute_name;
                newAttributeDropdown.appendChild(option);
            }
        });

        // Helper function to update or add filter in allFilters (new code)
        function updateFilterInAllFilters() {
            // Only add/update if attribute_name and attribute_value are selected
            if (filter.attribute_name && filter.attribute_value) {
                const index = allFilters.findIndex(f => f.index === filter.index);
                if (index > -1) {
                    allFilters[index] = {
                        ...filter
                    }; // Update existing filter
                } else {
                    allFilters.push({
                        ...filter
                    }); // Add new filter
                }
                addNewRowBtn.disabled = false;
                applyFilters();
            } else {
                addNewRowBtn.disabled = true;
            }
        }

        $(newAttributeDropdown).on('select2:select', (e) => {
            const selectedAttrName = e.target.value;
            const attriObj = contact_attributes.find(attr => attr.attribute_name === selectedAttrName);

            if (!attriObj) return;

            filter.attribute_name = attriObj?.attribute_name;

            // ❗ Reset attribute value when attribute name changes
            filter.attribute_value = '';
            // Clear previous values
            newAttributeValDropdown.innerHTML = `<option value="" disabled selected>Select a value</option>`;
            $(newAttributeValDropdown).val(null).trigger('change.select2'); // Reset UI

            // Parse JSON string of attribute values
            let values = [];
            try {
                values = JSON.parse(attriObj.attribute_value);
            } catch (err) {
                console.error("Failed to parse attribute values", err);
            }

            values.forEach(val => {
                const option = document.createElement("option");
                option.value = val;
                option.textContent = val;
                newAttributeValDropdown.appendChild(option);
            });
            newAttributeValDropdown.disabled = false;

            tryEnableValueDropdown();

            // Update filter list if operation and value already selected
            updateFilterInAllFilters();
        });

        $(newOperationDropdown).on('select2:select', (e) => {
            filter.operation = e.target.value;
            updateFilterInAllFilters();
        });

        $(newAttributeValDropdown).on('select2:select', (e) => {
            filter.attribute_value = e.target.value;
            updateFilterInAllFilters();
        });

        setTimeout(() => {
            $(newAttributeDropdown).select2({
                placeholder: "Select an attribute",
                theme: "bootstrap-5",
                width: '100%',
                dropdownParent: $('#filter-options'),
                minimumInputLength: 0
            });
            $(newOperationDropdown).select2({
                placeholder: "Select an operation",
                theme: "bootstrap-5",
                width: '100%',
                dropdownParent: $('#filter-options'),
                minimumInputLength: 0
            })
            $(newAttributeValDropdown).select2({
                placeholder: "Select a value",
                theme: "bootstrap-5",
                width: '100%',
                dropdownParent: $('#filter-options'),
                minimumInputLength: 0
            });
        }, 100);

        const deleteBtn = newRow.querySelector('.deleteContact');

        deleteBtn.addEventListener('click', () => {
            const domElm = deleteBtn.closest('.filter-row');
            const atttibute = domElm.querySelector(".attribute-names-select").value;
            const filterOptions = document.getElementById("filter-options"); //main parent container of fiter container and new filteration btn(used to add new filteration in filter container)

            if (domElm) {
                domElm.remove();
                allFilters = allFilters.filter((elm) => elm.attribute_name != atttibute);

                // Apply filters after removal
                applyFilters();

                if (filtersCon.children.length == 0) {
                    document.querySelector('.new-filter-btn').style.display = "none";
                    filterOptions.classList.add('d-none');
                }
            }
        });

        function tryEnableValueDropdown() {
            if (filter.attribute_name && filter.operation) {
                newAttributeValDropdown.disabled = false;
            }
        }
    }

    async function find_invalid_contacts() {
        try {
            const response = await fetch('https://app.watify.io/server/invalid_phone_numbers?find_invalid_contacts=1', {
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                throw new Error(`HTTP error ${response.status}`);
            }

            // const rawText = await response.text();
            // console.log(rawText); // inspect what's there
            // const result = JSON.parse(rawText);


            const result = await response.json();
            console.log(result);
            if(!result || result?.status === "error"){
                console.log("fail to fetch invalid contacts");
            }else if(result.invalidContacts.length===0){
                return;
            }

            const exclude_div = document.querySelector('.exclude-div');
            const invalid_contacts_dom = document.querySelectorAll(".invalid-contacts");
            const delete_invalid_contacts = document.getElementById("delete-invalid-contacts");
            
            exclude_div.classList.remove("d-none");
            
            invalid_contacts_dom.forEach((elm) => {
                elm.textContent = result.invalidContacts.length;
            });

            delete_invalid_contacts.addEventListener('click', () => {
                const invalid_contacts = result.invalidContacts;

                if (!invalid_contacts || invalid_contacts.length == 0) {
                    console.log("Either invalid_contacts field is missing or invalid_contacts is empty.");
                    return;
                }

                $.ajax({
                    url: "server/invalid_phone_numbers?delete_invalid_contacts=1",
                    method: "POST",
                    data: {
                        invalid_contacts: invalid_contacts.join(',')
                    }, // send as a CSV string
                    success: function(res) {

                        if(res.status == "success"){
                            round_success_noti(res.message);
                            setTimeout(()=>{
                                window.location.reload();
                            },3500);

                        }else{ //when status is error
                            round_error_noti("Something went wrong, Try again later!");
                            console.log("Error occur from backend while deleting invalid contacts...");
                            console.log(res.message);
                        }

                    },
                    error: function(xhr, status, error) {
                        round_error_noti("Something went wrong, Try again later!");
                        console.log(xhr.responseText);
                        console.log(error);
                        console.log("Error occur while deleting invalid contacts...");
                    }
                });
            });


        } catch (error) {
            console.error("Error occur while fetching invalid contacts...");
            console.log(error);
        }
    }
</script>

<script>
    $(document).ready(function() {
        // Stop form to submit
        document.getElementById("broadcast_form").addEventListener('submit', (e) => {
            e.preventDefault();
        })
        // Code to set Untitled_dateTime(like Untitled_2752025953)
        const broadcast_name = document.getElementById("simpleinput");
        if (broadcast_name) {
            const b_val = `Untitled_${new Date().getDate()}${new Date().getMonth()+1}${new Date().getFullYear()}${new Date().getHours()}${new Date().getMinutes()}`;
            broadcast_name.value = b_val;
        }

        // fetch client template
        $.ajax({
            url: 'https://app.watify.io/server/fetch_template?fetch_temp=1',
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                if (response && response.status === 'success' && response.data.length > 0) {
                    // console.log('Data received:', response.data); // Debugging

                    let options = '<option value="">Select Category</option>'; // Default option

                    // Loop through each template and add to the dropdown
                    response.data.forEach(function(template) {
                        options += `<option value="${template.id}">${template.template_name}</option>`;
                    });

                    $('#templateCategory').html(options); // Populate the dropdown
                } else {
                    console.log('Error:', response ? response.message : 'No response');
                    $('#templateCategory').html('<option value="">No templates found</option>'); // Handle empty case
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX Error:', status, error);
                console.log('Response Text:', xhr.responseText); // Log raw response for debugging
            }
        });

        // fetch contacts counting
        $.ajax({
            url: "server/fetch_template?contacts_count=1",
            method: "GET",
            success: function(res) {
                const count = res.data.total_contacts;
                document.getElementById("max-contant").textContent = count || 0;
            },
            error: function(status, xhr, error) {
                console.log(xhr);
                console.log(error);
            }
        })


        const filterBtn = document.getElementById('filter-btn'); // btn to add filteration
        const filtersCon = document.getElementById("filters-con"); // container where filteration will add
        const filterOptions = document.getElementById("filter-options"); //main parent container of fiter container and new filteration btn(used to add new filteration in filter container)
        const contactSearchInput = document.getElementById('contactSearchInput'); //search input where user can search contact
        const contactSearchIcon = document.getElementById('contact-search-icon'); //search icon, by click on it user can search contact
        const contact_table = document.getElementById("all_contacts_table").querySelector('tbody');

        // Attached event to filter button to enable or remove all filteration.
        filterBtn.addEventListener('click', function() {
            const contact_table = document.getElementById("all_contacts_table").querySelector('tbody');
            if (contact_table && contact_table?.children.length === 0) {
                return;
            }
            if (filterOptions.classList.contains("d-none")) {
                filterOptions.classList.remove("d-none");
                // console.log(filtersCon.children.length);
                if (filtersCon.children.length == 0) {
                    document.querySelector('.new-filter-btn').style.display = "block";
                    addNewRow();
                }
            } else {
                filterOptions.classList.add("d-none");
                filtersCon.innerHTML = "";
            }
        });



        // Filter contacts in the datatable based on the search input when the click on search icon.
        contactSearchIcon.addEventListener('click', () => {
            const searchVal = contactSearchInput.value.trim().toLowerCase(); // Trim & lowercase for safety

            if (searchVal == '') {
                contact_table.innerHTML = "";
                return;
            }
            let query = `(name LIKE '%${searchVal}%' or phone LIKE '%${searchVal}%')`;

            loadTable(1, query);
        });

        // Filter contacts in the datatable based on the search input when the Enter key is pressed.
        contactSearchInput.addEventListener('keyup', (e) => {
            if (e.key == "Enter") {
                const searchVal = contactSearchInput.value.trim().toLowerCase(); // Trim & lowercase for safety
                if (searchVal === '') {
                    contact_table.innerHTML = "";
                    allFilters = [];
                    document.getElementById("filters-con").innerHTML = "";
                    document.getElementById("filter-options").classList.add('d-none');
                    document.querySelector('.new-filter-btn').style.display = "none";
                    return;
                }

                let query = `(name LIKE '%${searchVal}%' or phone LIKE '%${searchVal}%')`;
                loadTable(1, query);
            }
        });


    });

    $(document).ready(function() {
        // Fetch attributes
        $.ajax({
            url: 'https://app.watify.io/server/fetch_template?contacts_attributes=1',
            type: 'GET',
            dataType: 'json',
            success: function(res) {
                if (!res.data || !Array.isArray(res.data)) {
                    console.log("data is invalid");
                    return;
                }
                contact_attributes = res.data;

            },
            error: function(xhr, status, error) {
                console.log("Error:", error);
                alert("Failed to fetch attributes.");
            }
        });

    });

    // fetch template details
    $('#templateCategory').change(function() {
        let selectedTemplateId = $(this).val(); // Get selected template ID

        if (selectedTemplateId) {
            $.ajax({
                url: 'https://app.watify.io/server/fetch_template_details', // Update with correct endpoint
                type: 'GET',
                data: {
                    template_id: selectedTemplateId
                }, // Send template ID as parameter
                dataType: 'json',
                success: function(response) {
                    if (response && response.status === 'success') {
                        console.log('Selected Template Data:', response.data);

                        let templateBody = response.data.template_body || 'No content available';
                        let templateFooter = response.data.template_footer || 'Powered by Watify.io';
                        let templateType = response.data.template_type;
                        let templateCopyText = response.data.copy_text || '';
                        let templateBtns = response.data.template_buttons;

                        // ✅ Insert the template body inside the preview
                        $('#preview-message-body-text').html(templateBody);

                        // ✅ Insert the footer text in the designated footer section
                        $('#preview-message-footer-text').html(`<p>${templateFooter}</p>`);

                        if (templateType == "standard") {
                            const btn_id = `button-${new Date()}`;

                            //preview-message-footer-links-container
                            $("#copy-button-preview-container").html(getPreviewContent(btn_id, "", "copy", templateCopyText));

                            if (templateBtns && templateBtns.length > 0) {
                                templateBtns.forEach((btn) => {
                                    if (btn.button_type == "visit-website") {
                                        $("#preview-visit-website-container").append(getPreviewContent(btn_id, "", "url", btn.text));
                                    } else {
                                        $("#quick-reply-button-preview-container").append(getPreviewContent(btn_id, "", "quickReply", btn.text));
                                    }
                                });
                            }
                        }
                    } else {
                        console.log('Error:', response ? response.message : 'No response');

                        // Handle empty case
                        $('#preview-message-body-text').html('<p>No details found</p>');
                        $('#preview-message-footer-text').html('');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX Error:', status, error);
                    console.log('Response Text:', xhr.responseText);
                }
            });
        } else {
            // Clear preview if no template is selected
            $('#preview-message-body-text').html('');
            $('#preview-message-footer-text').html('');
        }
    });

    // Btn to back all broadcast list
    const toggleBroadcast = document.getElementById("toggleBroadcast");

    toggleBroadcast.addEventListener('click', () => {
        document.getElementById("broadcastAnalytics").classList.remove("d-none");
        document.getElementById("anotherSection").classList.add("d-none");
    });

    // Btn to send new broadcast
    const newBroadcastBtn = document.querySelector(".new-broadcast-btn");

    newBroadcastBtn.addEventListener('click', () => {
        const broadcast_form = document.getElementById("broadcast_form");
        if (!broadcast_form) {
            round_error_noti("Something went wrong, Try again later!");
            console.log("Error: broadcast_form element not found.");
            return;
        }

        const formData = new FormData(broadcast_form);

        const broadcast_name = formData.get('broadcast_name')?.trim();
        const selected_template = formData.get('template_category');
        const send_type = formData.get('sendOption'); // removed trailing space

        const selected_contacts_elements = document.querySelectorAll("input.contactdata[type='checkbox']:checked");
        const selected_contacts = Array.from(selected_contacts_elements).map(elm => parseInt(elm.value));


        if (!broadcast_name) {
            round_error_noti("Please enter a broadcast name.");
            console.log("Validation failed: broadcast_name is empty.");
            return;
        }

        if (!selected_template) {
            round_error_noti("Please select a template.");
            console.log("Validation failed: template_category is not selected.");
            return;
        }

        if (selected_contacts.length === 0) {
            round_error_noti("Please select at least one contact.");
            console.log("Validation failed: no contacts selected.");
            return;
        }

        if (!send_type) {
            round_error_noti("Please choose Send Now or Schedule.");
            console.log("Validation failed: sendOption not selected.");
            return;
        }

        let schedule_date = null;
        let schedule_time = null;
        let schedule_at = "now";

        if (send_type === "send_schedule") {
            schedule_date = formData.get('schedule_date');
            schedule_time = formData.get('schedule_time');

            if (!schedule_date) {
                round_error_noti("Please select a schedule date.");
                console.log("Validation failed: schedule_date is empty.");
                return;
            }

            if (!schedule_time) {
                round_error_noti("Please select a schedule time.");
                console.log("Validation failed: schedule_time is empty.");
                return;
            }
            schedule_at = `${schedule_date} ${schedule_time}:00`;
        }

        // ✅ If all validations pass
        // console.log("Broadcast Name:", broadcast_name);
        // console.log("Selected Template:", selected_template);
        // console.log("Send Option:", sendOption);
        // console.log("Selected Contacts:", selected_contacts);
        // if (sendOption === "send_schedule") {
        //     console.log("Schedule Date:", schedule_date);
        //     console.log("Schedule Time:", schedule_time);
        // }

        $.ajax({
            // url: "server/add_broadcast",
            url: "server/broadcast?add_broadcast=1",
            method: "POST",
            data: {
                broadcast_name,
                selected_template,
                selected_contacts,
                send_type,
                schedule_at
            },
            success: function(res) {
                if (res.status == "error") {
                    round_error_noti("Failed to add broadcast, Try again later!");
                } else {
                    round_success_noti("Broadcast Added successfully!");
                }
                console.log(res);
            },
            error: function(xhr, status, error) {
                console.log(xhr.responseText);
                console.log(error);
                round_error_noti("Failed to add broadcast, Try again later!");
            }
        });
    });

    //Checkbox to select all contacts
    const select_all_checkbox = document.getElementById("selectAll"); //checkbox to select all checkbox

    select_all_checkbox.addEventListener('click',(e)=>{
        const all_checkbox = document.querySelectorAll('.contactdata');
        const val = e.target.checked;

        all_checkbox.forEach((checkbox)=>{
            if(!checkbox.closest('.disabled-row')){
                checkbox.checked = val;
            }
        }); 
    });

    // Find Invalid contacts
    find_invalid_contacts();
</script>