<?php require_once("./pin/header.php"); ?>
<?php require_once("./pin/navbar.php"); ?>
<?php require_once("./pin/sidebar.php"); ?>
<link
    rel="stylesheet"
    href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css" />

<style>
    .drag-and-drop-container {
        cursor: pointer;
        width: 100px;
        height: 100px;
        background-color: #f0f7ff;
        border: 2px dashed #c4c4c4;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 10px;
    }

    .carousel-card-selected {
        border: 3px solid green;
    }

    .plus-icon {
        position: relative;
        width: 30px;
        height: 30px;
    }

    .plus-icon div {
        position: absolute;
        background-color: #007bff;
        border-radius: 5px;
    }

    .plus-icon .vertical {
        width: 4px;
        height: 30px;
        top: 0;
        left: 13px;
    }

    .plus-icon .horizontal {
        width: 30px;
        height: 4px;
        top: 13px;
        left: 0;
    }

    .swiper {
        padding: 10px;
        border-radius: 10px;
        margin: 10px;
        background: white;
    }

    .swiper-slide {
        border-radius: 15px;
        overflow: hidden;
    }

    .swiper-slide-active {
        border: 4px solid green;
    }

    /* Style the navigation arrows */
    .swiper-button-next,
    .swiper-button-prev {
        background-color: rgba(0, 0, 0, 0.5);
        color: white;
        width: 30px;
        height: 30px;
        border-radius: 50%;
        transition: all 250ms ease-in-out;
    }

    /* Change arrow hover effect */
    .swiper-button-next:hover,
    .swiper-button-prev:hover {
        background-color: rgba(0, 0, 0, 0.8);
    }

    /* Style the next arrow */
    .swiper-button-next:after {
        font-size: 14px;
    }

    /* Style the prev arrow */
    .swiper-button-prev:after {
        font-size: 14px;
    }

    .createTemplate-fade-in {
        opacity: 0;
        transition: opacity 0.5s ease-in-out;
    }

    .createTemplate-show {
        opacity: 1;
    }

    option:disabled {
        cursor: not-allowed;
    }

    .deleteButton {
        background: red !important;
        transition: all 250ms ease-in-out;
    }

    .deleteButton:hover {
        background: #ff0000ab !important;
    }

    .addButtonPlus {
        background: rgb(10, 129, 36) !important;
        transition: all 250ms ease-in-out;
    }

    .addButtonPlus:hover {
        background: rgba(23, 139, 48, 0.9) !important;
    }

    .green-button {
        background: #86EFAC;
        transition: all 250ms ease-in-out;
        color: #15803D;
        outline: none;
        border: 1px solid #15803D;
        border-radius: 5px;
    }

    .green-button:hover {
        background: #22C55E;
    }

    .buttons-select-options {
        display: block;
        width: 8.4rem;
    }

    .newTemplateForm {
        max-height: 80vh;
        overflow: auto;
    }

    .newTemplateForm::-webkit-scrollbar,
    .preview-message::-webkit-scrollbar {
        width: 2px;
        /* Width of the scrollbar */
    }

    .newTemplateForm::-webkit-scrollbar-track,
    .preview-message::-webkit-scrollbar {
        background: #f1f1f1;
        border-radius: 10px;
    }

    .newTemplateForm::-webkit-scrollbar-thumb,
    .preview-message::-webkit-scrollbar {
        background: #888;
        /* Thumb color */
        border-radius: 10px;
    }

    .newTemplateForm::-webkit-scrollbar-thumb:hover,
    .preview-message::-webkit-scrollbar {
        background: #555;
        /* Thumb color on hover */
    }

    .preview-message-container,
    #auth-copy-button-container {
        background: #fff;
        width: 200px;
        padding: 8px;
        border-radius: 10px;
        margin-left: 10px;
        margin-top: 10px;
        overflow-wrap: break-word;
    }

    .inputbgcolor {
        background-color: #f5f6fa;
    }

    .preview-message-container p,
    #auth-copy-button-container p {
        margin-bottom: 0px;
    }

    .preview-message-container p:last-child,
    #auth-copy-button-container p:last-child {
        margin-bottom: 5px;
    }

    .button-container {
        display: flex;
        gap: 10px;
    }

    .option-button {
        display: flex;
        align-items: center;
        padding: 8px 12px;
        background-color: white;
        border: 1px solid #e0e0e0;
        border-radius: 6px;
        cursor: pointer;
        font-size: 14px;
        color: #333;
        transition: all 0.2s ease;
        position: relative;
    }

    .option-button:hover {
        background-color: #f9f9f9;
    }

    .option-button.selected {
        border: 2px solid #0a8124;
        padding: 7px 11px;
    }

    .option-button .icon {
        margin-right: 8px;
        display: flex;
        align-items: center;
        opacity: 0.7;
    }

    .pro-badge {
        display: inline-block;
        background-color: #f2efe4;
        color: #b09245;
        font-size: 10px;
        font-weight: bold;
        padding: 2px 4px;
        border-radius: 3px;
        margin-left: 6px;
    }

    .fade-animation-class {
        animation: fade-in 0.4s ease-out;
    }

    @keyframes fade-in {
        0% {
            opacity: 0;
        }

        100% {
            opacity: 1;
        }
    }

    .editMessageTemplate:hover svg {
        fill: white !important;
    }

    .deleteMessageTemplate:hover svg {
        fill: white !important;
    }
</style>
<div class="content-page">
    <div class="content" id="allTemplates">

        <!-- Start Content-->
        <div class="container-fluid">
            <!------------------ Dummy view of all templates ------------------>
            <!-- <div class="py-3 d-flex align-items-sm-center flex-sm-row flex-column">
                <div class="flex-grow-1">
                    <h4 class="fs-18 fw-semibold m-0">Your Templates</h4>
                    <p class="m-0">Select or create your template and submit it for WhatsApp approval. All templates must adhere to <a href="#" class="text-decoration-underline"> WhatsApp's guidelines </a>.</p>
                </div>
                <div>
                    <button class="btn btn-success" id="addNewTemplate">Add New Template</button>
                </div>
            </div> -->
            <!-- <div class="row">
                <div class="col-xl-12">
                    <div class="card overflow-hidden">

                        <div class="card-body mt-0">
                            <div class="table-responsive table-card mt-0">
                                <table
                                    class="table table-borderless table-centered align-middle table-nowrap mb-0">
                                    <thead class="text-muted table-light">
                                        <tr>
                                            <th scope="col" class="cursor-pointer">Lead</th>
                                            <th scope="col" class="cursor-pointer">Email</th>
                                            <th scope="col" class="cursor-pointer">Phone No</th>
                                            <th scope="col" class="cursor-pointer">Campany</th>
                                            <th scope="col" class="cursor-pointer">Status</th>
                                            <th scope="col" class="cursor-pointer">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td>
                                                <img src="assets/images/users/user-22.jpg"
                                                    class="avatar avatar-sm rounded-circle me-3">
                                                John Hamilton
                                            </td>
                                            <td>johnehamilton@gmail.com</td>
                                            <td>+48, 65610085</td>
                                            <td>Mufti</td>
                                            <td>
                                                <span class="badge bg-primary-subtle text-primary fw-semibold">New Lead</span>
                                            </td>
                                            <td>
                                                <a aria-label="anchor"
                                                    class="btn btn-icon btn-sm bg-primary-subtle me-1"
                                                    data-bs-toggle="tooltip" data-bs-original-title="Edit">
                                                    <i class="mdi mdi-pencil-outline fs-14 text-primary"></i>
                                                </a>
                                                <a aria-label="anchor"
                                                    class="btn btn-icon btn-sm bg-danger-subtle"
                                                    data-bs-toggle="tooltip" data-bs-original-title="Delete">
                                                    <i class="mdi mdi-delete fs-14 text-danger"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>
                                                <img src="assets/images/users/user-23.jpg"
                                                    class="avatar avatar-sm rounded-circle me-3">
                                                Janice Reese
                                            </td>
                                            <td>janicecreese@gmail.com</td>
                                            <td>+45, 32678972</td>
                                            <td>Gucci</td>
                                            <td>
                                                <span
                                                    class="badge bg-secondary-subtle text-secondary fw-semibold">In
                                                    Progress</span>
                                            </td>
                                            <td>
                                                <a aria-label="anchor"
                                                    class="btn btn-icon btn-sm bg-primary-subtle me-1"
                                                    data-bs-toggle="tooltip" data-bs-original-title="Edit">
                                                    <i class="mdi mdi-pencil-outline fs-14 text-primary"></i>
                                                </a>
                                                <a aria-label="anchor"
                                                    class="btn btn-icon btn-sm bg-danger-subtle"
                                                    data-bs-toggle="tooltip" data-bs-original-title="Delete">
                                                    <i class="mdi mdi-delete fs-14 text-danger"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>
                                                <img src="assets/images/users/user-19.jpg"
                                                    class="avatar avatar-sm rounded-circle me-3">
                                                Andrew Kim
                                            </td>
                                            <td>andrewekim@gmail.com</td>
                                            <td>+30, 84787124</td>
                                            <td>Vans</td>
                                            <td>
                                                <span
                                                    class="badge bg-danger-subtle text-danger fw-semibold">Loss</span>
                                            </td>
                                            <td>
                                                <a aria-label="anchor"
                                                    class="btn btn-icon btn-sm bg-primary-subtle me-1"
                                                    data-bs-toggle="tooltip" data-bs-original-title="Edit">
                                                    <i class="mdi mdi-pencil-outline fs-14 text-primary"></i>
                                                </a>
                                                <a aria-label="anchor"
                                                    class="btn btn-icon btn-sm bg-danger-subtle"
                                                    data-bs-toggle="tooltip" data-bs-original-title="Delete">
                                                    <i class="mdi mdi-delete fs-14 text-danger"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>
                                                <img src="assets/images/users/user-20.jpg"
                                                    class="avatar avatar-sm rounded-circle me-3">
                                                Kathryn Sanchez
                                            </td>
                                            <td>kathryntsanchez@gmail.com</td>
                                            <td>+30, 23794209</td>
                                            <td>Myntra</td>
                                            <td>
                                                <span
                                                    class="badge bg-success-subtle text-success fw-semibold">Won</span>
                                            </td>
                                            <td>
                                                <a aria-label="anchor"
                                                    class="btn btn-icon btn-sm bg-primary-subtle me-1"
                                                    data-bs-toggle="tooltip" data-bs-original-title="Edit">
                                                    <i class="mdi mdi-pencil-outline fs-14 text-primary"></i>
                                                </a>
                                                <a aria-label="anchor"
                                                    class="btn btn-icon btn-sm bg-danger-subtle"
                                                    data-bs-toggle="tooltip" data-bs-original-title="Delete">
                                                    <i class="mdi mdi-delete fs-14 text-danger"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>
                                                <img src="assets/images/users/user-21.jpg"
                                                    class="avatar avatar-sm rounded-circle me-3">
                                                Diane Richards
                                            </td>
                                            <td>dianetrichards@gmail.com</td>
                                            <td>+78, 37569176</td>
                                            <td>HCLTech</td>
                                            <td>
                                                <span
                                                    class="badge bg-warning-subtle text-warning fw-semibold">Converted</span>
                                            </td>
                                            <td>
                                                <a aria-label="anchor"
                                                    class="btn btn-icon btn-sm bg-primary-subtle me-1"
                                                    data-bs-toggle="tooltip" data-bs-original-title="Edit">
                                                    <i class="mdi mdi-pencil-outline fs-14 text-primary"></i>
                                                </a>
                                                <a aria-label="anchor"
                                                    class="btn btn-icon btn-sm bg-danger-subtle"
                                                    data-bs-toggle="tooltip" data-bs-original-title="Delete">
                                                    <i class="mdi mdi-delete fs-14 text-danger"></i>
                                                </a>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>

                    </div>
                </div>

            </div> -->

            <div class="py-3 d-flex align-items-sm-baseline flex-sm-row flex-column">
                <div class="flex-grow-1">
                    <h2 class="fw-bold m-0">Your Templates</h2>
                    <p class="m-0">Select or create your template and submit it for WhatsApp approval. All templates must adhere to <a href="#" style="text-decoration: underline;">WhatsApp's guidelines</a></p>
                </div>
                <div class="d-flex align-items-baseline" style="gap:1rem;">
                    <div>
                        <img src="https://archive.org/download/mx-player-icon/mx-player-icon.png" alt="error" style="width: 2rem;" />
                        <span style="cursor:pointer; color: #4285F4;">Watch Tutorial</span>
                    </div>
                    <div>
                        <button class="btn btn-success" id="addNewTemplate" data-bs-toggle="modal">New Template Message</button>
                        <p class="mb-0 mt-3 fw-bold text-dark" id="messageTemplatesCount"></p>
                    </div>
                </div>
            </div>
            <div class="py-3 d-flex align-items-sm-center justify-content-between flex-sm-row flex-column">
                <div>
                    <div class="d-flex align-items-center gap-2">
                        <div>
                            <h6 class="fw-bold m-0">Sorted by:</h6>
                        </div>
                        <div>
                            <select class="form-select" name="custom_sort" id="custom_sort">
                                <option value="template_name">Name</option>
                                <option value="created_at">Created Date</option>
                            </select>
                        </div>

                        <div class="dropdown status_dropdown" data-bs-auto-close="outside">
                            <button class="btn d-flex justify-content-between align-items-center" type="button"
                                data-bs-toggle="dropdown" aria-expanded="false"
                                style="background-color: white; border: 1px solid lightgrey; border-radius: 5px; width: 160px; padding: 8px 12px;">
                                <span>Status</span>
                                <svg xmlns="http://www.w3.org/2000/svg" width="11" height="16" fill="currentColor" style="stroke: #0000008c;"
                                    class="bi bi-chevron-down ms-2" viewBox="0 0 16 16">
                                    <path fill-rule="evenodd"
                                        d="M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z" />
                                </svg>
                            </button>
                            <ul class="dropdown-menu p-3" style="min-width: 250px;">
                                <li>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" value="draft" id="status_draft">
                                        <label class="form-check-label" for="status_draft">Draft</label>
                                    </div>
                                </li>
                                <li>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" value="pending" id="status_pending">
                                        <label class="form-check-label" for="status_pending">Pending</label>
                                    </div>
                                </li>
                                <li>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" value="approved" id="status_approved">
                                        <label class="form-check-label" for="status_approved">Approved</label>
                                    </div>
                                </li>
                                <li>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" value="rejected" id="status_rejected">
                                        <label class="form-check-label" for="status_rejected">Rejected</label>
                                    </div>
                                </li>
                                <li>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" value="deleted" id="status_deleted">
                                        <label class="form-check-label" for="status_deleted">Deleted</label>
                                    </div>
                                </li>
                                <li>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" value="paused" id="status_paused">
                                        <label class="form-check-label" for="status_paused">Paused</label>
                                    </div>
                                </li>
                                <li>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" value="disabled" id="status_disabled">
                                        <label class="form-check-label" for="status_disabled">Disabled</label>
                                    </div>
                                </li>
                            </ul>
                        </div>

                        <div>
                            <div class="input-group">
                                <input type="text" class="form-control" placeholder="Search Message Templates..." aria-label="Search Message Templates..." aria-describedby="basic-addon2" id="searchInput">
                                <span class="input-group-text" style="cursor: pointer;" id="searchIcon"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" style="fill: rgb(133 133 133);">
                                        <path d="M19.023 16.977a35.13 35.13 0 0 1-1.367-1.384c-.372-.378-.596-.653-.596-.653l-2.8-1.337A6.962 6.962 0 0 0 16 9c0-3.859-3.14-7-7-7S2 5.141 2 9s3.14 7 7 7c1.763 0 3.37-.66 4.603-1.739l1.337 2.8s.275.224.653.596c.387.363.896.854 1.384 1.367l1.358 1.392.604.646 2.121-2.121-.646-.604c-.379-.372-.885-.866-1.391-1.36zM9 14c-2.757 0-5-2.243-5-5s2.243-5 5-5 5 2.243 5 5-2.243 5-5 5z"></path>
                                    </svg></span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="d-flex align-items-center justify-content-center gap-4">
                    <div>
                        <div style="background: #fff;padding: 8px 15px;border-radius: 25px;display: flex;justify-content: center;align-items: center;gap: 10px;">
                            <a href="#" class="text-dark" data-bs-toggle="modal" data-bs-target="#exportMessageTemplateModal"><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="M11 16h2V7h3l-4-5-4 5h3z"></path>
                                    <path d="M5 22h14c1.103 0 2-.897 2-2v-9c0-1.103-.897-2-2-2h-4v2h4v9H5v-9h4V9H5c-1.103 0-2 .897-2 2v9c0 1.103.897 2 2 2z"></path>
                                </svg> Export</a>
                            |
                            <a href="#" class="text-dark" data-bs-toggle="modal" data-bs-target="#importMessageTemplateModal"><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 18 4-5h-3V2h-2v11H8z"></path>
                                    <path d="M19 9h-4v2h4v9H5v-9h4V9H5c-1.103 0-2 .897-2 2v9c0 1.103.897 2 2 2h14c1.103 0 2-.897 2-2v-9c0-1.103-.897-2-2-2z"></path>
                                </svg> Import</a>
                        </div>
                    </div>

                    <div style="border: 1px solid red;padding: 5px;border-radius: 5px;cursor: pointer;">
                        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" style="fill: rgb(255 0 0);">
                            <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>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-xl-12">
                    <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 class="table-responsive table-card mt-0" id="all_message_templates_div">
                                <table id="all_message_templates" 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">Template Name</th>
                                            <th scope="col" class="cursor-pointer">Category</th>
                                            <!-- <th scope="col" class="cursor-pointer">Source</th> -->
                                            <th scope="col" class="cursor-pointer text-center">Status</th>
                                            <th scope="col" class="cursor-pointer">Language</th>
                                            <th scope="col" class="cursor-pointer">Last Updated</th>
                                            <th scope="col" class="cursor-pointer text-center">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>

                                    </tbody>
                                </table><!-- end table -->
                            </div>
                        </div>

                    </div>
                </div>

            </div>
        </div>
    </div>

    <!----------------------------------- Create New Template ----------------------------------->
    <div class="content d-none" id="createTemplate">

        <!-- Start Content-->
        <div class="container-fluid">
            <div class="pt-3 d-flex align-items-sm-center flex-sm-row flex-column">
                <div class="flex-grow-1">
                    <div class="d-flex align-items-center gap-2">
                        <div onclick="navigateToTemplateList(); clearPreviousTemplateData(); loadTable()" style="cursor: pointer;">
                            <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>
                        </div>
                        <h4 class="fs-18 fw-semibold m-0">
                            New Templates
                        </h4>
                    </div>
                </div>
                <div>
                    <button class="btn btn-outline-success me-2">Save as draft</button>
                    <button class="btn btn-success" id="save-submit">Save and submit</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" id="template_editor">
                                <form action="">
                                    <div class="row template-name-category-main">
                                        <div class="col-sm-4">
                                            <div class="mb-3">
                                                <label for="template-name" class="form-label fw-bold">Template Name</label>
                                                <input
                                                    type="text"
                                                    id="template-name"
                                                    name="templateName"
                                                    class="form-control inputbgcolor"
                                                    placeholder="Template Name"
                                                    oninput="templateTopValuesChange(event)">
                                            </div>
                                        </div>
                                        <div class="col-sm-4">
                                            <div class="mb-3">
                                                <label for="category" class="form-label fw-bold">Category</label>
                                                <select class="form-select inputbgcolor" name="category" id="category" onchange="templateTopValuesChange(event)">
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-sm-4">
                                            <div class="mb-3">
                                                <label for="language" class="form-label fw-bold">Language</label>
                                                <select class="form-select inputbgcolor" name="language" id="language" onchange="templateTopValuesChange(event)">
                                                    <option value="">Select Language</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    <div id="marketing-template-section">
                                        <div class="mb-3">
                                            <label for="standard" class="form-label fw-bold">Select Marketing template</label>
                                            <div class="button-container">
                                                <button data-marketing-template="standard" type="button" class="option-button" id="standard" onclick="marketingTemplateValueChange(event)">
                                                    <span class="icon">
                                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                            <rect x="4" y="4" width="16" height="16" rx="1" stroke="currentColor" stroke-width="2" />
                                                            <line x1="8" y1="9" x2="16" y2="9" stroke="currentColor" stroke-width="2" />
                                                            <line x1="8" y1="12" x2="16" y2="12" stroke="currentColor" stroke-width="2" />
                                                            <line x1="8" y1="15" x2="12" y2="15" stroke="currentColor" stroke-width="2" />
                                                        </svg>
                                                    </span>
                                                    <input type="radio" checked class="market-template" hidden value="Standard">
                                                    Standard
                                                </button>

                                                <!-- <button data-marketing-template="catalog" type="button" class="option-button" id="catalog" onclick="marketingTemplateValueChange(event)">
                                                        <span class="icon">
                                                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                                <rect x="4" y="6" width="16" height="12" rx="1" stroke="currentColor" stroke-width="2" />
                                                                <path d="M8 10H16M8 14H16" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
                                                            </svg>
                                                        </span>
                                                        Catalog
                                                    </button> -->

                                                <button data-marketing-template="carousel" type="button" class="option-button" id="carousel" onclick="marketingTemplateValueChange(event)">
                                                    <span class="icon">
                                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                            <rect x="3" y="6" width="18" height="12" rx="1" stroke="currentColor" stroke-width="2" />
                                                            <rect x="6" y="9" width="12" height="6" rx="1" stroke="currentColor" stroke-width="2" />
                                                        </svg>
                                                    </span>
                                                    <input type="radio" class="market-template" hidden value="Carousel">
                                                    Carousel
                                                    <span class="pro-badge">PRO</span>
                                                </button>

                                                <button data-marketing-template="limited-time-offers" type="button" class="option-button" id="limited" onclick="marketingTemplateValueChange(event)">
                                                    <span class="icon">
                                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                            <circle cx="12" cy="12" r="9" stroke="currentColor" stroke-width="2" />
                                                            <path d="M12 7V12L15 15" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
                                                        </svg>
                                                    </span>
                                                    <input type="radio" class="market-template" hidden value="Limited time offers">
                                                    Limited time offers
                                                    <span class="pro-badge">PRO</span>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    <hr />
                                    <div id="broadcast-title-section">
                                        <div class="mb-3">
                                            <label for="none" class="form-label fw-bold">Broadcast title</label> <span>(Optional)</span>
                                            <p>Highlight your brand here, use images or videos, to stand out</p>

                                            <div class="col-sm-10 d-flex gap-2">
                                                <div class="form-checkm me-2">
                                                    <input class="form-check-input first-broadcast-checkbox" type="radio" name="broadcastTitleRadio" id="none" value="" checked onchange="onBroadCastTitleChange(event)">
                                                    <label class="form-check-label" for="none">
                                                        None
                                                    </label>
                                                </div>

                                                <div class="form-check me-4">
                                                    <input class="form-check-input broadcast-checkbox" type="radio" name="broadcastTitleRadio" id="text" value="text" onchange="onBroadCastTitleChange(event)">
                                                    <label class="form-check-label" for="text">
                                                        Text
                                                    </label>
                                                </div>
                                                <div class="form-check me-4">
                                                    <input class="form-check-input broadcast-checkbox" type="radio" name="broadcastTitleRadio" id="image" value="image" onchange="onBroadCastTitleChange(event)">
                                                    <label class="form-check-label" for="image">
                                                        Image
                                                    </label>
                                                </div>
                                                <div class="form-check me-4">
                                                    <input class="form-check-input broadcast-checkbox" type="radio" name="broadcastTitleRadio" id="video" value="video" onchange="onBroadCastTitleChange(event)">
                                                    <label class="form-check-label" for="video">
                                                        Video
                                                    </label>
                                                </div>
                                                <div class="form-check me-4">
                                                    <input class="form-check-input broadcast-checkbox" type="radio" name="broadcastTitleRadio" id="document" value="document" onchange="onBroadCastTitleChange(event)">
                                                    <label class="form-check-label" for="document">
                                                        Document
                                                    </label>
                                                </div>
                                            </div>

                                            <div>
                                                <div id="broadcast-title-preview-type" class="d-flex gap-1 align-items-center"></div>

                                                <div id="broadcast-title-radio-input-type" class="d-flex gap-1 align-items-center"></div>
                                            </div>
                                        </div>

                                        <hr />
                                    </div>
                                    <div id="template-body-section">
                                        <div class="mb-3">
                                            <label for="simpleinput" class="form-label fw-bold">Body</label>
                                            <p>Make your messages personal using variables like <span class="text-primary">{{name}}</span> and get more replies!</p>
                                            <div class="row">
                                                <div class="col-12">
                                                    <div class="">
                                                        <div id="quill-editor" class="inputbgcolor standard-quill body-text-box" style="height: 200px;" aria-placeholder="Template Message...">

                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div id="carousel-section" style="display: none;">
                                            <h5><span style="color: #000000;">Carousel cards</span> (<span id="carousel-card-length">0</span>/5)</h5>

                                            <p>Display your products - create a carousel of images and buttons for up to 5 cards. <a href="">Learn more</a></p>

                                            <div class="d-flex my-3 gap-3" id="carousel-item-container"></div>

                                            <div class="drag-and-drop-container" onclick="addCarousel(event)">
                                                <div class="plus-icon">
                                                    <div class="vertical"></div>
                                                    <div class="horizontal"></div>
                                                </div>
                                            </div>
                                            <div id="edit-carousel-section-container">
                                            </div>
                                        </div>

                                        <div class="form-check" id="auth-security-checkbox" style="display: none;">
                                            <input class="form-check-input" type="checkbox" value="" id="authSecurityCheckbox" onchange="onAuthSecurityRecommendationChange(event)">
                                            <label class="form-check-label" for="authSecurityCheckbox">
                                                Add security recommendation
                                            </label>
                                        </div>
                                    </div>
                                    <hr />
                                    <div id="template-footer-section">
                                        <div class="mb-3">
                                            <label for="previewMessageFooterInput" class="form-label fw-bold">Footer</label> <span>(Optional)</span>
                                            <p>Footers are great to add any disclaimers or to add a thoughtful PS</p>
                                            <input type="text" id="previewMessageFooterInput" class="form-control inputbgcolor" placeholder="Footer Text" value="Powered by watify.io">
                                        </div>

                                        <hr />
                                    </div>

                                    <div class="form-check mb-1" id="expiry-time-checkbox" style="display: none;">
                                        <input class="form-check-input" type="checkbox" value="" id="expiryTimeCheckbox" onchange="onExpiryTimeChange(event)">
                                        <label class="form-check-label" for="expiryTimeCheckbox">
                                            Include expiry time
                                        </label>
                                    </div>

                                    <div id="expiry-time-value" style="width: 9rem;  display: none;">
                                        <div class="d-flex align-items-center gap-2">
                                            <div class="input-group">
                                                <input
                                                    class="form-control"
                                                    max="90"
                                                    min="1"
                                                    value="10"
                                                    type="number"
                                                    id="expiry-time-input"
                                                    onchange="onExpiryTimeValueChange(event)">
                                            </div>

                                            <p class="m-0">minutes</p>
                                        </div>
                                    </div>


                                    <div id="buttons-section">
                                        <div class="mb-3">
                                            <label for="" class="form-label fw-bold" style="color: black;">Buttons</label> <span class="fw-bold">(Recommended)</span>
                                            <p>Insert buttons so your customers can take action and engage with your message!</p>
                                            <div>
                                                <div class="mb-2 gap-2" id="add-visit-website-btn-con">
                                                    <div id="add-button-container" class="position-relative"></div>
                                                    <div id="addWebsiteCallButtonContainer" class="d-flex mb-2 gap-2">
                                                        <button type="button" class="btn btn-outline-success" id="addWebsiteCallButton">Add Visit Website button</button>
                                                    </div>
                                                </div>

                                                <div id="copy-button-section">
                                                    <div id="copy-button-container" class="position-relative">

                                                    </div>

                                                    <div class="d-flex mb-2 gap-2" id="copyButtonContainer">
                                                        <button id="copyButton" type="button" class="btn btn-outline-success">Add Copy button</button>
                                                    </div>
                                                </div>

                                                <div id="quick-reply-section">
                                                    <div id="quick-reply-button-container" class="position-relative"></div>

                                                    <div class="d-flex mb-2 gap-2" id="quickRepliesButtonContainer">
                                                        <button type="button" id="addQuickRepliesButton" class="btn btn-outline-success">Add Quick Replies button</button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div id="buttons-authentication-section" style="display: none;">
                                        <div class="mb-3">
                                            <label for="" class="form-label fw-bold" style="color: black;">Buttons</label>
                                            <p>Add text for users to easily copy the code.</p>

                                            <div class="input-group">
                                                <input
                                                    type="text"
                                                    maxlength="25"
                                                    minlength="1"
                                                    value="Copy"
                                                    oninput="onAuthButtonTextChange(event)"
                                                    class="form-control authButtonTextInput"
                                                    placeholder="Enter text">

                                                <span class="input-group-text">
                                                    <span class="authButtonInputTextCharacters">4</span> / 25
                                                </span>
                                            </div>
                                        </div>
                                    </div>

                                    <div id="sample-content-section" class="mb-3">
                                        <label for="sample-content" class="form-label fw-bold">Sample Content</label>
                                        <p>Just enter sample content here (it doesn't need to be exact!)</p>

                                        <div class="input-group">
                                            <input
                                                id="sample-content"
                                                type="text"
                                                maxlength="200"
                                                minlength="1"
                                                oninput="onSampleContentTextChange(event)"
                                                class="form-control sampleContentTextInput"
                                                placeholder="Enter content for variable, e.g. {{name}}">

                                            <span class="input-group-text">
                                                <span class="sampleContentInputTextCharacters">0</span> / 200
                                            </span>
                                        </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;">Powered by watify.io</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>
                                    </div>

                                    <div class="" id="auth-copy-button-container" style="font-size: 14px; background: white; margin-top: 5px; display: none;">
                                        <div id="auth-copy-button-preview" style="max-width: 200px; text-align: center; overflow: hidden; direction: initial;font-size: inherit; color: #2b65ff; font-weight: 600;">Copy</div>
                                    </div>

                                    <div class="rounded-2 p-1" id="carousel-container" style="display: none;">
                                        <div class="swiper">
                                            <!-- Additional required wrapper -->
                                            <div class="swiper-wrapper">
                                                <!-- Slides -->
                                            </div>
                                            <!-- If we need pagination -->
                                            <!-- <div class="swiper-pagination"></div> -->

                                            <!-- If we need navigation buttons -->
                                            <div class="swiper-button-prev"></div>
                                            <div class="swiper-button-next"></div>

                                            <!-- If we need scrollbar -->
                                            <!-- <div class="swiper-scrollbar"></div> -->
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div> <!-- container-fluid -->
    </div> <!-- content -->

    <!-- Footer Start -->
    <footer class="footer">
        <div class="container-fluid">
            <div class="row">
                <div class="col fs-13 text-muted text-center">
                    &copy; <script>
                        document.write(new Date().getFullYear())
                    </script> - Made with <span class="mdi mdi-heart text-danger"></span> by <a href="#!" class="text-reset fw-semibold">Watify.io</a>
                </div>
            </div>
        </div>
    </footer>
    <!-- end Footer -->

</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>
<script src="./JS/carousel.js"></script>

<!-- Swiper JavaScript -->
<script>
    const swiper = new Swiper('.swiper', {
        // Optional parameters
        direction: 'horizontal',
        loop: false,

        // If we need pagination
        pagination: {
            el: '.swiper-pagination',
        },

        // Navigation arrows
        navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
        },

        slidesPerView: 1,
        spaceBetween: 20,

        // And if we need scrollbar
        scrollbar: {
            el: '.swiper-scrollbar',
        },
    });
</script>

<script>
    const myTemplate = {};

    let editContentId = "";

    const optionButtons = document.querySelectorAll('.option-button');

    function onCarouselMediaUpload(e, idx) {
        const file = e.currentTarget.files[0];

        // Check image extension must be webp
        if (!file) {
            e.currentTarget.value = "";
            return;
        }
        const preview = URL.createObjectURL(file);

        carouselCardData[editContentId]["mediaURL"] = preview;
        const mediaType = carouselCardData[editContentId]["mediaType"];
        // const btn_preview_con = `
        // <div class="text-dark" class="carousel-preview-message-footer-links-container">
        //             <div class="carousel-preview-visit-website-container d-flex gap-3 justify-content-center my-2"></div>
        //             <div class="carousel-quick-reply-button-preview-container d-flex flex-column justify-content-center my-2"></div>
        //         </div>
        // `;

        if (mediaType === "image") {
            //Restriction that check image size is not more than 2 mb.
            if (file.type !== 'image/webp') {
                round_error_noti('Only .webp images are allowed!');
                e.currentTarget.value = "";
                return;
            }
            // const file = e.currentTarget.files[0];
            const maxSize = 2 * 1024 * 1024;

            if (file && file.size > maxSize) {
                round_error_noti('File size must be less than 2MB');
                e.currentTarget.value = "";
                return;
            }
            const image = `<div style="width: 24rem; height: 18rem; background: url(${carouselCardData[editContentId]["mediaURL"]}); background-repeat: no-repeat; background-size: cover; background-position: center;"></div>`;
            const styles = {
                background: `url(${carouselCardData[editContentId]["mediaURL"]})`,
                backgroundRepeat: "no-repeat",
                backgroundPosition: "center",
                backgroundSize: "cover"
            };

            $(`#${editContentId}`).css(styles);

            $(`div[data-slider-id=${editContentId}]`).children().first().css(styles);
            // $(`#carousel-card-media-${idx}`).empty().append(image, btn_preview_con);
            $(`#carousel-card-media-${idx} div`).remove(); //previous image that set in div bg
            $(`#carousel-card-media-${idx}`).prepend(image);
        } else if (mediaType === "video") {

            if (file.type !== "video/mov" && file.type !== "video/mp4") {
                round_error_noti('Only .mov and .mp4 videos are allowed!');
                e.currentTarget.value = "";
                return;
            }
            const video_edit_comp = `<video class="w-50 rounded-3" src="${carouselCardData[editContentId]["mediaURL"]}" autoplay muted loop></video>`;
            const video = `<video style="width:100%;" class="rounded-3" src="${carouselCardData[editContentId]["mediaURL"]}" autoplay muted loop></video>`;
            const video_slider_card = `<video style="width:100%; height: 100%; object-fit: cover;" class="rounded-3" src="${carouselCardData[editContentId]["mediaURL"]}" autoplay muted loop></video>`;
            let val = e.currentTarget.id.split('-');
            $(`#carousel-card-media-${val[val.length-1]}`).html(video_edit_comp);
            // $(`.swiper-slide-${idx}`).empty().append(video, btn_preview_con);
            $(`.swiper-slide-${idx} video`).remove();
            $(`.swiper-slide-${idx} .slider-card-img-div`).remove();
            $(`.swiper-slide-${idx}`).prepend(video);
            $(`.slider-card-num-${idx}`).empty().append(video_slider_card);
        }
    }

    function onCarouselMediaTypeChange(e, idx) {
        const {
            value,
            id
        } = e.currentTarget;
        // const val = id.split('-');
        // const i = val[val.length-1];

        $(`#carousel-card-media-${idx}`).html("");
        $(`#carousel-upload-media-${idx}`).val("");

        // const slides_img_css = "background: url(https://app.watify.io/images/dummy-image.webp);";
        // $(`.swiper-slide-${idx}`).prepend(slides_img);

        const slides_img = `<div class="
        slider-card-img-div " style="
        background: url(https://app.watify.io/images/dummy-image.webp);
        background-repeat: no-repeat;
        background-position: center;
        background-size: cover;
        height: 9rem;
        margin: 3px;
        border-radius: 10px;
        "></div>`;

        carouselCardData[editContentId]["mediaType"] = value;

        const mediaType = carouselCardData[editContentId]["mediaType"];

        $(`.swiper-slide-${idx} video`).remove();
        $(`.swiper-slide-${idx} .slider-card-img-div`).remove();
        $(`.swiper-slide-${idx}`).prepend(slides_img);
        // $(`.swiper-slide-${idx}`).css("background-image", "url('https://app.watify.io/images/dummy-image.webp')");

        $(`.slider-card-num-${idx} video`).remove();
        $(`.slider-card-num-${idx}`).css("background-image", "url('https://app.watify.io/images/dummy-image.webp')");

        if (mediaType === "image") {
            // if (document.querySelector(`.swiper-slide-${idx}`).querySelector('video')) {
            // }
            // $(`#carousel-upload-media-${i}`).attr("accept", ".png, .jpeg, .jgp, .gif");
            $(`#carousel-upload-media-${idx}`).attr("accept", ".webp");
        } else if (mediaType === "video") {
            $(`#carousel-upload-media-${idx}`).attr("accept", ".mov, .mp4");
            // const video_div = document.querySelector(`.swiper-slide-${idx} video`);

            // if (video_div) {
            //     video_div.remove();
            // }
            // document.querySelector(`.slider-card-num-${idx}`).style.background = 'url(https://app.watify.io/images/dummy-image.webp) center/cover no-repeat';
            // document.querySelector(`.swiper-slide-${idx} > div`).style.background = 'url(https://app.watify.io/images/dummy-image.webp) center/cover no-repeat';
        }
    }

    function onBroadCastTitleChange(e) {
        const value = e.currentTarget.value;

        if (e.currentTarget.checked) {
            if (value === "text") {
                $("#broadcast-title-preview-type").html("");

                $("#broadcast-title-radio-input-type").html(getBroadCastTitleInput("", 60, "text", "onBroadCastTextInputChange"))

                $("#broadcast-title-container").html(`<h4 style="font-weight: 700; color: black;"></h4>`);

            } else if (value === "image") {

                $("#broadcast-title-preview-type").html(getBroadCastTitleImagePreview("images/dummy-image.webp", `broadcast-title-${value}-preview`))

                $("#broadcast-title-radio-input-type").html(getBroadCastTitleInput("", 2000, "image", "onBroadCastImageInputChange"));

                $("#broadcast-title-container").html(getBroadCastTitleImage("images/dummy-image.webp"));

            } else if (value === "video") {
                const videoURL = "https://storage.googleapis.com/gtv-videos-bucket/sample/ForBiggerMeltdowns.mp4";

                $("#broadcast-title-preview-type").html(getBroadCastTitleImagePreview("images/video-dummy-image.svg", `broadcast-title-${value}-preview`, "video"))

                $("#broadcast-title-radio-input-type").html(getBroadCastTitleInput("", 2000, "video", "onBroadCastVideoInputChange"));

                $("#broadcast-title-container").html(getBroadCastTitleImage("images/video-dummy-image.svg"));

            } else if (value === "document") {
                $("#broadcast-title-preview-type").html(getBroadCastTitleImagePreview("images/document-dummy-image.svg", `broadcast-title-${value}-preview`, "document"));

                $("#broadcast-title-radio-input-type").html(getBroadCastTitleInput("", 2000, "document", "onBroadCastDocumentInputChange"))

                $("#broadcast-title-container").html(getBroadCastTitleImage("images/document-dummy-image.svg"));

            } else if (value === "") {
                $("#broadcast-title-preview-type").html("");

                $("#broadcast-title-radio-input-type").html("");

                $("#broadcast-title-container").html("");

            }
        }
    }

    function hideShowSections(type = "hide", ...sectionIDs) {
        const allSections = [
            "broadcast-title-section",
            "buttons-section",
            "template-footer-section",
            "template-body-section",
            "marketing-template-section"
        ];

        (sectionIDs[0] === "all" ? allSections : sectionIDs).forEach((sectionID) => {
            if (type === "show") {
                $(`#${sectionID}`).css({
                    display: "block"
                });
            } else {
                $(`#${sectionID}`).css({
                    display: "none"
                });
            }
        });
    }

    function templateTopValuesChange(e) {
        const {
            name,
            value
        } = e.currentTarget;


        myTemplate[name] = value;

        if (name === "category") {
            if (value === "utility") {
                hideShowSections(
                    "hide",
                    "marketing-template-section",
                    "copy-button-section",
                    "buttons-authentication-section",
                    "auth-security-checkbox",
                    "expiry-time-checkbox",
                    "expiry-time-value",
                    "auth-copy-button-container"
                );

                hideShowSections(
                    "show",
                    "broadcast-title-section",
                    "buttons-section"
                );

                $("#previewMessageFooterInput").val("Powered by watify.io");
                $("#preview-message-footer-text").val("Powered by watify.io");

                const predefinedBody = `Hi {{name}},\nReminder to confirm your appointment with us! Please click the link below\nThank you`;

                quill.root.innerHTML = predefinedBody;

                previewMessageBodyText.innerHTML = predefinedBody;

                showSampleContent(quill.root.innerHTML);

                insertSpanInPreviewMessage(quill.root.innerHTML);
            } else if (value === "marketing") {
                hideShowSections(
                    "show",
                    "marketing-template-section",
                    "broadcast-title-section",
                    "buttons-section",
                    "copy-button-section"
                );
                hideShowSections(
                    "hide",
                    "buttons-authentication-section",
                    "auth-copy-button-container",
                    "expiry-time-checkbox",
                    "expiry-time-value",
                    "auth-security-checkbox"
                );

                quill.root.innerHTML = "";

                $("#previewMessageFooterInput").val("Powered by watify.io");
                $("#preview-message-footer-text").val("Powered by watify.io");

                previewMessageBodyText.innerHTML = "";

                showSampleContent(quill.root.innerHTML);

                insertSpanInPreviewMessage(quill.root.innerHTML);
            } else if (value === "authentication") {
                const predefinedBodyForAuth = `{{1}} is your verification code.`;

                hideShowSections(
                    "hide",
                    "broadcast-title-section",
                    "buttons-section"
                );
                hideShowSections(
                    "show",
                    "buttons-authentication-section",
                    "auth-copy-button-container",
                    "expiry-time-checkbox",
                    "auth-security-checkbox"
                );

                $("#previewMessageFooterInput").val("");
                $("#preview-message-footer-text").val("");

                quill.root.innerHTML = predefinedBodyForAuth;

                previewMessageBodyText.innerHTML = predefinedBodyForAuth;
                showSampleContent(quill.root.innerHTML);
                insertSpanInPreviewMessage(quill.root.innerHTML);
            }
        }
    }

    function showSampleContent(bodyText) {
        const variableConstraint = /\{\{[A-Za-z0-9]+\}\}/;

        const isShown = variableConstraint.test(bodyText);

        $("#sample-content-section").css({
            display: isShown ? "block" : "none"
        })
    }

    function insertSpanInPreviewMessage(bodyText) {
        const variableConstraint = /\{\{[A-Za-z0-9]+\}\}/;
        const isShown = variableConstraint.test(bodyText);
        if (isShown) {
            const dynamicVariable = previewMessageBodyText.innerHTML.match(variableConstraint)[0];

            const newPreviewBody = previewMessageBodyText.innerHTML.replace(variableConstraint, `<span class="dynamic-variable">${dynamicVariable}</span>`);

            previewMessageBodyText.innerHTML = newPreviewBody;
        }
    }

    function onExpiryTimeChange(e) {
        hideShowSections(e.currentTarget.checked ? "show" : "hide", "expiry-time-value")

        if (e.currentTarget.checked) {
            const footerContent = `This code expires in 10 minutes.`;

            $("#preview-message-footer-text").html(footerContent);
            $("#previewMessageFooterInput").val(footerContent);
        } else {
            $("#preview-message-footer-text").html("");
            $("#previewMessageFooterInput").val("");
        }
    }

    function onExpiryTimeValueChange(e) {
        const value = e.currentTarget.value;

        const footerValue = $("#previewMessageFooterInput").val();

        const newFooterValue = footerValue.replace(/[0-9]+/, value);

        $("#previewMessageFooterInput").val(newFooterValue);
        $("#preview-message-footer-text").html(newFooterValue);
    }

    function onAuthSecurityRecommendationChange(e) {
        const additionalString = " For your security, do not share this code.";

        if (e.currentTarget.checked) {
            quill.insertText(additionalString);

            previewMessageBodyText.innerHTML = quill.root.innerHTML;
        } else {
            if (quill.getText().includes(additionalString)) {
                quill.setText(quill.getText().split(".")[0]);

                previewMessageBodyText.innerHTML = quill.root.innerHTML;
            }
        }
    }


    function getCarouselItem(id, backgroundURL, index) {
        return `
                <div id="${id}" data-index="${index}" class="slider-card slider-card-num-${index}" onclick="showCardEditContent(event)" style="cursor: pointer; width: 100px; height: 100px; background: url(${backgroundURL}); background-position: center;  background-size: cover; background-repeat: no-repeat; border-radius: 10px;"></div>
            `;
    }

    function getSliderItem(dataId, backgroundURL, index) {
        return `
                <div data-slider-id="${dataId}" data-index="${index}" class="swiper-slide swiper-slide-${index}">
                    <div class="slider-card-img-div" style="background: url(${backgroundURL}); background-repeat: no-repeat; background-position: center; background-size: cover; height: 9rem; margin: 3px; border-radius: 10px;"></div>

                    <div class="text-dark" class="carousel-preview-message-footer-links-container">
                        <div class="carousel-preview-visit-website-container d-flex gap-3 justify-content-center my-2"></div>
                        <div class="carousel-quick-reply-button-preview-container d-flex flex-column justify-content-center my-2"></div>
                    </div>
                </div>
            `;
    }

    function showCardEditContent(e) {
        document.querySelectorAll(".slider-card").forEach((slider) => {
            slider.classList.remove("carousel-card-selected");
        })
        const slider_card = e.target.closest('.slider-card');
        slider_card.classList.add("carousel-card-selected");

        editContentId = slider_card.getAttribute("id");

        const index = slider_card.getAttribute("data-index");

        swiper.slideTo(parseFloat(index));

        const editContentCon = document.getElementById('edit-carousel-section-container');

        Array.from(editContentCon.children).forEach((elm) => {
            if (elm.classList.contains(editContentId)) {
                elm.style.display = "block";
            } else {
                elm.style.display = "none";
            }
        });


        $(".carousel-delete-button").attr("data-carousel-id", editContentId);

        // const mediaType = carouselCardData[editContentId]["mediaType"];

        // if (mediaType === "image") {
        //     document.getElementById("carousel-image").checked;
        // } else if (mediaType === "video") {
        //     document.getElementById("carousel-video").checked;
        // }
    }

    function onAuthButtonTextChange(e) {
        const value = e.currentTarget.value;

        $(".authButtonInputTextCharacters").html(value.length);

        $("#auth-copy-button-preview").html(value);

    }

    function onSampleContentTextChange(e) {
        const variableConstraint = /\{\{[A-Za-z0-9]+\}\}/;

        const value = e.currentTarget.value;

        $(".sampleContentInputTextCharacters").html(value.length);

        if (value) {
            $(".dynamic-variable").html(value);
        } else {
            $(".dynamic-variable").html(quill.getText().match(variableConstraint)[0]);
        }
    }


    function marketingTemplateValueChange(e) {
        const currentButton = e.currentTarget;
        const dataMarketingTemplate = currentButton.getAttribute("data-marketing-template");

        optionButtons.forEach(button => {
            button.classList.remove('selected');
        });


        myTemplate["marketingTemplate"] = dataMarketingTemplate;
        currentButton.classList.add('selected');

        if (dataMarketingTemplate === "carousel") {
            hideShowSections(
                "hide",
                "template-footer-section",
                "buttons-section",
                "broadcast-title-section"
            );

            if (document.querySelectorAll(".slider-card").length > 0) {
                // sections to show in standard template
                hideShowSections(
                    "show",
                    "carousel-section",
                    "carousel-container"
                );
            } else {
                hideShowSections(
                    "show",
                    "carousel-section"
                );
            }
        } else if (dataMarketingTemplate === "standard") {
            hideShowSections(
                "show",
                "template-footer-section",
                "buttons-section",
                "broadcast-title-section"
            );

            // sections to hide in standard template
            hideShowSections(
                "hide",
                "carousel-section",
                "carousel-container"
            );
        }

        const x = document.querySelectorAll('.market-template');
        x.forEach((elm) => {
            elm.checked = false;
        });
        e.currentTarget.querySelector('input').checked = true;
    }

    function getResetPreviewButton(type) {
        return `
                <button 
                    id="${type}-reset-preview-button" 
                    data-type="${type}" 
                    type="button" 
                    class="btn mt-2 btn-outline-danger deleteCopyButton deleteButton" 
                    style="color: white; width: 7rem; padding: 0.34rem 0.4rem; border-radius: 5px; display: none;" 
                    onclick="removePreview(event)"
                >
                    Remove
                </button>
            `;
    }

    function getBroadCastTitleImage(url) {
        return `
                <div class="rounded-3 mb-2" style="background: url('${url}'); background-repeat: no-repeat; background-position: center; height: 9rem; background-size: cover;"></div>
            `;
    }

    function getBroadCastTitleImagePreview(url, imageID, optionalType = "image") {
        return `
                <div class="mb-2 mt-3 d-flex flex-column">
                    <img id="${imageID}" class="w-50 rounded-3" src="${url}" alt="broadcast-title-image" />

                    ${getResetPreviewButton(optionalType)}
                </div>
            `;
    }

    function getBroadCastTitleVideo(url) {
        return `
                <div class="mb-2" style="overflow: hidden;">
                    <video src="${url}" class="w-100 h-100 rounded-3" autoplay muted loop></video>

                    ${getResetPreviewButton("video")}
                </div>
            `;
    }

    function getBroadCastTitleVideoPreview(url, videoID, optionalType = "video") {
        return `
                <div class="mb-2 mt-3 position-relative d-flex flex-column">
                    <video id="${videoID}" class="w-50 rounded-3" src="${url}" autoplay muted loop></video>

                    ${getResetPreviewButton(optionalType)}
                </div>
            `;
    }

    function getBroadCastTitleDocument(url) {
        if (url) {
            return `
                    <iframe src="${url}" class="rounded-3" title="Document.PDF" style="height: 9rem; width: 100%;"></iframe>
                `;
        } else {
            return `
                    <div class="rounded-3 my-2" style="background: url(images/document-dummy-image.svg); background-repeat: no-repeat; background-position: center; height: 12rem; background-size: cover;"></div>
                `;
        }
    }

    function getBroadCastTitleDocumentPreview(url, documentID, optionalType = "document") {
        return `
                <div class="mt-3 mb-2" style="width: 30%;">
                    <iframe src="${url}" class="rounded-3" id="${documentID}" title="Document.PDF" style="height: 9rem; width: 100%;"></iframe>

                    ${getResetPreviewButton(optionalType)}
                </div>
            `;
    }

    function getBroadCastTitleInput(inputValue, length, type, eventName) {
        const imageSupportedFormats = "image/jpg, image/jpeg, image/png, image/gif";
        const videoSupportedFormats = "video/mp4, video/3gp, video/mov";
        const documentSupportedFormats = ".pdf";

        if (type === "text") {
            return `
                <div class="input-group ${type}-input-of-broadcast-title mt-3">
                    <input 
                        type="text" 
                        maxlength="${length}" 
                        value="${inputValue}"
                        oninput="${eventName}(event)"
                        class="form-control broadcastTitleInputMedia" 
                        data-broadcast-title-type="${type}"
                        placeholder="${type === "text" ? "Enter Text" : "Enter Link"}"
                    >

                    <span class="input-group-text">
                        <span class="broadcastTitleCharactersCount">${inputValue.length}</span> / ${length}
                    </span>
                </div>
            `;
        } else if (type === "image" || type === "video" || type === "document") {
            return `
                <div class="d-flex justify-content-between w-100 mt-3 align-items-center">
                    <div class="input-group ${type}-input-of-broadcast-title  w-75">
                        <input 
                            id="image-url-input" 
                            type="text" 
                            maxlength="${length}" 
                            value="${inputValue}"
                            oninput="${eventName}(event)"
                            onblur="sanitizeURL(event)"
                            class="form-control broadcastTitleInput" 
                            data-broadcast-title-type="${type}"
                            placeholder="${type === "text" ? "Enter Text" : "Enter Link"}"
                        >

                        <span class="input-group-text">
                            <span class="broadcastTitleCharactersCount">${inputValue.length}</span> / ${length}
                        </span>
                    </div>

                    <p class="m-0">
                        or
                    </p>

                    <div class="${type}-input-of-broadcast-title">
                        <input 
                        type="file" 
                        accept="${type === "video" ? videoSupportedFormats : type === "image" ? imageSupportedFormats : documentSupportedFormats}"
                        id="${type}-input-of-broadcast-title-id"
                        onchange="${eventName}(event)"
                        class="form-control broadcastTitleInputMedia" 
                        data-broadcast-title-type="${type}"
                        hidden
                        >

                        <label for="${type}-input-of-broadcast-title-id" class="btn btn-outline-success addButtonPlus" style="color: white; padding: 0.34rem 0.4rem; border-radius: 5px; right: 0; top: 0;">
                            Upload Media
                        </label>
                    </div>
                </div>
            `;
        }
    }

    function onBroadCastTextInputChange(e) {
        const value = e.currentTarget.value;

        e.currentTarget.closest(".text-input-of-broadcast-title").querySelector(".broadcastTitleCharactersCount").textContent = value.length;
        document.querySelector("#broadcast-title-container h4").textContent = value;
    }

    function resetOnInsecureURL(type, eventName, defaultURL, callback, callbackPreview) {
        $("#broadcast-title-preview-type").html(callbackPreview(defaultURL, `broadcast-title-${type}-preview`))

        $("#broadcast-title-radio-input-type").html(getBroadCastTitleInput("", 2000, type, eventName));

        $("#broadcast-title-container").html(callback(defaultURL));
    }

    function sanitizeURL(e) {
        if (e.currentTarget.value.startsWith("http://")) {
            const type = e.currentTarget.getAttribute("data-broadcast-title-type");

            if (type === "image") {
                resetOnInsecureURL(
                    type,
                    "onBroadCastImageInputChange",
                    "images/dummy-image.webp",
                    getBroadCastTitleImage,
                    getBroadCastTitleImagePreview
                );
            } else if (type === "video") {
                resetOnInsecureURL(
                    type,
                    "onBroadCastVideoInputChange",
                    "https://storage.googleapis.com/gtv-videos-bucket/sample/ForBiggerMeltdowns.mp4",
                    getBroadCastTitleVideo,
                    getBroadCastTitleVideoPreview
                );
            } else if (type === "document") {
                resetOnInsecureURL(
                    type,
                    "onBroadCastDocumentInputChange",
                    "images/document-dummy-image.svg",
                    getBroadCastTitleImage,
                    getBroadCastTitleDocumentPreview
                );
            }

            round_error_noti("Insecure resources is loaded via URL")
        }
    }

    function onBroadCastImageInputChange(e) {
        let globalValue = "";

        if (e.currentTarget.type === "file") {
            const files = e.currentTarget.files;
            let isImageError = false;

            if (files) {
                const file = files[0];

                if (file && file.size > 5 * 1024 * 1024) {
                    isImageError = true;
                    round_error_noti('Image size must not exceed 5 MB');
                    e.currentTarget.value = ''; // Fix: use e.currentTarget instead of input
                    return;
                }

                const allowedFormats = ['image/jpeg', 'image/png', 'image/jpeg', 'image/gif'];
                if (!allowedFormats.includes(file.type)) {
                    round_error_noti('Only JPEG, PNG, JPG and GIF formats are allowed');
                    e.currentTarget.value = '';
                    isImageError = true;
                    return;
                }

                const img = new Image();
                img.src = URL.createObjectURL(file);

                img.onload = () => {
                    if (img.width > 4096 || img.height > 4096) {
                        isImageError = true;
                        round_error_noti('Image dimensions must not exceed 4096 x 4096 pixels');
                        e.currentTarget.value = '';
                        return;
                    }
                };

                img.onerror = function() {
                    isImageError = true;
                    round_error_noti('Invalid image file');
                    e.currentTarget.value = '';
                };

                if (isImageError) {
                    return;
                }

                const preview = URL.createObjectURL(file);
                globalValue = preview;

                // Disable the URL input
                const urlInput = document.getElementById("image-url-input");
                if (urlInput) {
                    urlInput.disabled = true;
                    urlInput.value = "";
                }

                $("#broadcast-title-image-preview").attr("src", preview || "images/dummy-image.webp");
                $("#broadcast-title-container").html(getBroadCastTitleImage(preview || "images/dummy-image.webp"));
            }
        } else {
            const value = e.currentTarget.value;
            globalValue = value;

            // Disable the file input
            const fileInput = document.getElementById("image-file-input");
            if (fileInput) {
                fileInput.disabled = true;
            }

            e.currentTarget.closest(".image-input-of-broadcast-title")
                .querySelector(".broadcastTitleCharactersCount").textContent = value.length;

            $("#broadcast-title-image-preview").attr("src", value || "images/dummy-image.webp");
            $("#broadcast-title-container").html(getBroadCastTitleImage(value || "images/dummy-image.webp"));
        }

        if (globalValue) {
            $("#image-reset-preview-button").css({
                display: "inline"
            });
        } else {
            $("#image-reset-preview-button").css({
                display: "none"
            });
        }
    }


    function onBroadCastVideoInputChange(e) {
        let globalValue = "";

        const type = e.currentTarget.getAttribute("data-broadcast-title-type");

        if (e.currentTarget.type === "file") {
            const files = e.currentTarget.files;

            if (files) {
                const file = files[0];

                if (file && file.size > 2 * 1024 * 1024) {
                    e.currentTarget.value = "";
                    round_error_noti("File size is too big, please upload smaller video");
                    return;
                }

                const preview = URL.createObjectURL(file);

                globalValue = preview;
            }
        } else {
            const value = e.currentTarget.value;

            globalValue = value;

            e.currentTarget.closest(".video-input-of-broadcast-title").querySelector(".broadcastTitleCharactersCount").textContent = value.length;
        }

        if (globalValue) {
            $("#broadcast-title-preview-type").html(getBroadCastTitleVideoPreview(globalValue, `broadcast-title-${type}-preview`))

            $("#broadcast-title-container").html(getBroadCastTitleVideo(globalValue));

            $(`#video-reset-preview-button`).css({
                display: "inline"
            });
        } else {
            $("#broadcast-title-preview-type").html(getBroadCastTitleImagePreview("images/video-dummy-image.svg", `broadcast-title-${type}-preview`, "video"))

            $("#broadcast-title-container").html(getBroadCastTitleImage("images/video-dummy-image.svg"));

            $(`#video-reset-preview-button`).css({
                display: "none"
            });
        }
    }

    function removePreview(e) {
        const type = e.currentTarget.getAttribute("data-type");

        if (type === "document") {
            $("#broadcast-title-preview-type").html(getBroadCastTitleImagePreview("images/document-dummy-image.svg", `broadcast-title-${type}-preview`, "video"))

            $("#broadcast-title-radio-input-type").html(
                getBroadCastTitleInput(
                    "",
                    2000,
                    type,
                    "onBroadCastDocumentInputChange"
                )
            );

            $("#broadcast-title-container").html(getBroadCastTitleImage("images/document-dummy-image.svg"));
        } else if (type === "image") {
            $(`#broadcast-title-${type}-preview`).attr("src", "images/dummy-image.webp");

            $("#broadcast-title-radio-input-type").html(
                getBroadCastTitleInput(
                    "",
                    2000,
                    type,
                    "onBroadCastImageInputChange"
                )
            );

            $("#broadcast-title-container").html(getBroadCastTitleImage("images/dummy-image.webp"));
        } else if (type === "video") {

            $("#broadcast-title-preview-type").html(getBroadCastTitleImagePreview("images/video-dummy-image.svg", `broadcast-title-${type}-preview`, "video"))

            $("#broadcast-title-radio-input-type").html(
                getBroadCastTitleInput(
                    "",
                    2000,
                    type,
                    "onBroadCastVideoInputChange"
                )
            );

            $("#broadcast-title-container").html(getBroadCastTitleImage("images/video-dummy-image.svg"));
        }
        edit_template['removed_media'] = true;
        $(e.currentTarget).css({
            display: "none"
        });
    }

    function onBroadCastDocumentInputChange(e) {
        let globalValue = "";

        const type = e.currentTarget.getAttribute("data-broadcast-title-type");

        if (e.currentTarget.type === "file") {
            const files = e.currentTarget.files;

            if (files) {
                const file = files[0];

                if (file.size > 2 * 1024 * 1024) {
                    e.currentTarget.value = "";
                    round_error_noti("File size is too big, please upload smaller document");
                    return;
                }

                const preview = URL.createObjectURL(file);

                globalValue = preview;
            }
        } else {
            const value = e.currentTarget.value;

            globalValue = value;

            e.currentTarget.closest(".document-input-of-broadcast-title").querySelector(".broadcastTitleCharactersCount").textContent = value.length;
        }

        if (globalValue) {
            $("#broadcast-title-preview-type").html(getBroadCastTitleDocumentPreview(globalValue, `broadcast-title-${type}-preview`))

            $("#broadcast-title-container").html(getBroadCastTitleDocument(globalValue));

            $(`#document-reset-preview-button`).css({
                display: "inline"
            });
        } else {
            $("#broadcast-title-preview-type").html(getBroadCastTitleImagePreview("images/document-dummy-image.svg", `broadcast-title-${type}-preview`, "video"))

            $("#broadcast-title-container").html(getBroadCastTitleImage("images/document-dummy-image.svg"));

            $(`#document-reset-preview-button`).css({
                display: "none"
            });
        }
    }

    function getCopyButtonItem(dataTarget, inputValue, coupon_code = "") {
        return `
                <div class="d-flex flex-column gap-2 mb-2 copy-button-container-item">
                    <div class="d-flex align-items-center gap-2">
                        <div class="d-flex justify-content-between align-items-center">
                            <div class="d-flex gap-1 align-items-center">
                                <div class="input-group">
                                    <input 
                                    type="text" 
                                    maxlength="25" 
                                    minlength="1" 
                                    value="${inputValue}"
                                    oninput="onCopyButtonTextChange(event)"
                                    class="form-control copyButtonTextInput" 
                                    placeholder="Copy offer code"
                                    >

                                    <span class="input-group-text">
                                        <span class="copyButtonInputTextCharacters">${inputValue.length}</span> / 25
                                    </span>
                                </div>
                                <button data-target="${dataTarget}" type="button" class="btn btn-outline-danger deleteCopyButton deleteButton" style="padding: 0.34rem 0.4rem; border-radius: 5px;">
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" color="#ffffff" fill="none" style="height: 1.3rem; width: 1.3rem;">
                                        <path d="M19.5 5.5L18.8803 15.5251C18.7219 18.0864 18.6428 19.3671 18.0008 20.2879C17.6833 20.7431 17.2747 21.1273 16.8007 21.416C15.8421 22 14.559 22 11.9927 22C9.42312 22 8.1383 22 7.17905 21.4149C6.7048 21.1257 6.296 20.7408 5.97868 20.2848C5.33688 19.3626 5.25945 18.0801 5.10461 15.5152L4.5 5.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
                                        <path d="M3 5.5H21M16.0557 5.5L15.3731 4.09173C14.9196 3.15626 14.6928 2.68852 14.3017 2.39681C14.215 2.3321 14.1231 2.27454 14.027 2.2247C13.5939 2 13.0741 2 12.0345 2C10.9688 2 10.436 2 9.99568 2.23412C9.8981 2.28601 9.80498 2.3459 9.71729 2.41317C9.32164 2.7167 9.10063 3.20155 8.65861 4.17126L8.05292 5.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
                                        <path d="M9.5 16.5L9.5 10.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
                                        <path d="M14.5 16.5L14.5 10.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
                                    </svg>
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="d-flex align-items-center gap-2">
                        <div class="d-flex gap-1 align-items-center">
                            <div class="input-group">
                                <input 
                                type="text" 
                                maxlength="15"
                                value = "${coupon_code}" 
                                oninput="onCopyButtonCodeToCopyChange(event)"
                                class="form-control" 
                                placeholder="Enter coupon code to copy"
                                >
                                <span class="input-group-text">
                                    <span class="copyButtonCodeToCopyCharacters">${inputValue.length}</span> / 15
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            `;
    }

    function getQuickReplyButtonItem(dataTarget, inputValue) {
        return `
                <div class="d-flex w-75 gap-2 mb-2 align-items-center quick-reply-button-container-item">
                    <div class="input-group">
                        <input 
                            type="text" 
                            maxlength="25" 
                            class="form-control" 
                            name="quick_reply_title"
                            value="${inputValue}"
                            oninput="onQuickReplyButtonTextChange(event)" 
                            placeholder="Quick reply button Text"
                        >
                        <span class="input-group-text">
                            <span class="quickReplyInputCharacters">${inputValue.length}</span> / 25
                        </span>
                    </div>
                    
                    <button data-target="${dataTarget}" type="button" class="btn btn-outline-danger deleteQuickRepliesButton deleteButton" style="padding: 0.34rem 0.4rem; border-radius: 5px;">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" color="#ffffff" fill="none" style="height: 1.3rem; width: 1.3rem;">
                            <path d="M19.5 5.5L18.8803 15.5251C18.7219 18.0864 18.6428 19.3671 18.0008 20.2879C17.6833 20.7431 17.2747 21.1273 16.8007 21.416C15.8421 22 14.559 22 11.9927 22C9.42312 22 8.1383 22 7.17905 21.4149C6.7048 21.1257 6.296 20.7408 5.97868 20.2848C5.33688 19.3626 5.25945 18.0801 5.10461 15.5152L4.5 5.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
                            <path d="M3 5.5H21M16.0557 5.5L15.3731 4.09173C14.9196 3.15626 14.6928 2.68852 14.3017 2.39681C14.215 2.3321 14.1231 2.27454 14.027 2.2247C13.5939 2 13.0741 2 12.0345 2C10.9688 2 10.436 2 9.99568 2.23412C9.8981 2.28601 9.80498 2.3459 9.71729 2.41317C9.32164 2.7167 9.10063 3.20155 8.65861 4.17126L8.05292 5.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
                            <path d="M9.5 16.5L9.5 10.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
                            <path d="M14.5 16.5L14.5 10.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
                        </svg>
                    </button>
                </div>
            `;
    }

    function getAddWebsiteButtonInput(inputValue) {

        return `
            <div class="input-group">
                <input 
                    type="text" 
                    maxlength="25" 
                    minlength="1" 
                    class="form-control addWebsiteButtonTextInput" 
                    value="${inputValue}" 
                    oninput="onAddWebsiteButtonTextChange(event)" 
                    aria-label="Amount (to the nearest dollar)" 
                    placeholder="Enter the button text"
                >

                <span class="input-group-text">
                    <span class="addWebsiteButtonTextCharacters">${inputValue.length}</span> / 25
                </span>
            </div>
        `;
    }

    function getAddWebsiteButtonURLElements(buttonURL, button_content_type) {
        return `
            <select class="form-select inputbgcolor buttons-select-options" name="" id="" value="${button_content_type}">
                <option value="static">Static</option>
                <option value="dynamic">Dynamic</option>
            </select>
            <div class="d-flex gap-1 align-items-center">
                <div class="input-group">
                    <input 
                        type="text" 
                        maxlength="2000"
                        name="url"
                        value="${buttonURL}" 
                        oninput="onAddWebsiteButtonURLChange(event)" 
                        class="form-control addWebsiteButtonURLInput" 
                        aria-label="Amount (to the nearest dollar)" 
                        placeholder="Enter the button URL"
                    >
                    <span class="input-group-text">
                        <span class="addWebsiteButtonURLCharacters">${buttonURL.length}</span> / 2000
                    </span>
                </div>
            </div>
        `;
    }

    function getAddWebsiteButtonPhoneInput(inputValue) {

        return `
            <select class="form-select inputbgcolor buttons-select-options" style="opacity: 0;" disabled="true" name="">
                <option value="static">Static</option>
                <option value="dynamic">Dynamic</option>
            </select>
            <div class="d-flex gap-1 align-items-center">
                <div class="input-group">
                    <input 
                        type="tel" 
                        maxlength="10" 
                        name="phone"
                        value="${inputValue}" 
                        oninput="onAddWebsiteButtonURLChange(event)" 
                        class="form-control addWebsiteButtonPhoneInput" 
                        placeholder="Enter the phone number"
                    >

                    <span class="input-group-text">
                        <span class="addWebsiteButtonURLCharacters">${inputValue.length}</span> / 10
                    </span>
                </div>
            </div>
        `;
    }

    function toggleDisableSelectOptions(parentSelect, urlCount, phoneCount) {
        const options = parentSelect.querySelectorAll("option");

        options.forEach(option => {
            if (option.value === "url") {
                if (urlCount >= 2) {
                    option.disabled = true;
                } else {
                    option.disabled = false;
                }
            } else if (option.value === "phone") {
                if (phoneCount >= 1) {
                    option.disabled = true;
                } else {
                    option.disabled = false;
                }
            }
        })
    }

    function getURLPhoneSelectDetails(disableOptionsToo) {
        const URLPhoneSelectElements = document.getElementsByClassName("URLPhoneSelect");

        const object = {
            "url": 0,
            "phone": 0,
        };

        URLPhoneSelectElements.forEach(element => {
            object[element.value]++;
        })

        if (disableOptionsToo) {
            URLPhoneSelectElements.forEach(element => {
                toggleDisableSelectOptions(element, object.url, object.phone);
            })
        }

        return object;
    }

    function getAddWebsiteButtonContent(dataTarget, inputValue, buttonURL, type, button_content_type) {
        return `
                <div class="d-flex flex-column gap-2 mb-2 add-button-container-item">
                    <div class="d-flex align-items-center gap-2">
                        <select class="form-select inputbgcolor buttons-select-options URLPhoneSelect" onchange="onAddWebsiteOptionChange(event)" name="URLPhoneSelect">
                            <option value="url" ${type === "url" ? "selected" : ""}>Visit Website</option>
                            <option value="phone" ${type === "phone" ? "selected" : ""}>Call Phone</option>
                        </select>
                        <div class="d-flex justify-content-between align-items-center">
                            <div class="d-flex gap-2 align-items-center">

                                ${getAddWebsiteButtonInput(inputValue, "url")}

                                <button data-target="${dataTarget}" type="button" class="btn btn-outline-danger deleteWebsiteCallButton deleteButton" style="padding: 0.34rem 0.4rem; border-radius: 5px;">
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" color="#ffffff" fill="none" style="height: 1.3rem; width: 1.3rem;">
                                        <path d="M19.5 5.5L18.8803 15.5251C18.7219 18.0864 18.6428 19.3671 18.0008 20.2879C17.6833 20.7431 17.2747 21.1273 16.8007 21.416C15.8421 22 14.559 22 11.9927 22C9.42312 22 8.1383 22 7.17905 21.4149C6.7048 21.1257 6.296 20.7408 5.97868 20.2848C5.33688 19.3626 5.25945 18.0801 5.10461 15.5152L4.5 5.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
                                        <path d="M3 5.5H21M16.0557 5.5L15.3731 4.09173C14.9196 3.15626 14.6928 2.68852 14.3017 2.39681C14.215 2.3321 14.1231 2.27454 14.027 2.2247C13.5939 2 13.0741 2 12.0345 2C10.9688 2 10.436 2 9.99568 2.23412C9.8981 2.28601 9.80498 2.3459 9.71729 2.41317C9.32164 2.7167 9.10063 3.20155 8.65861 4.17126L8.05292 5.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
                                        <path d="M9.5 16.5L9.5 10.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
                                        <path d="M14.5 16.5L14.5 10.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
                                    </svg>
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="d-flex align-items-center gap-2 addWebsiteButtonURLAndPhoneContainer">
                        ${type === "url" ? getAddWebsiteButtonURLElements(buttonURL, button_content_type) : getAddWebsiteButtonPhoneInput(buttonURL)}
                    </div>
                </div>
            `;
    }

    const addVisitWebsiteButton = `
        <button type="button" class="btn btn-outline-success" id="addWebsiteCallButton">Add Visit Website button</button>
        `;

    function getPlusButton(action) {
        const object = {};

        if (action === "url") {
            object["id"] = "addVisitWebsiteButtonPlus";
            object["clickEvent"] = "addWebsiteCallButtonListener()";
        } else {
            object["id"] = "addQuickReplyButtonPlus";
            object["clickEvent"] = "addQuickRepliesButtonListener()";
        }

        return `
                <button type="button" class="btn position-absolute btn-outline-success addButtonPlus" id="${object.id}" onclick="${object.clickEvent}" style="padding: 0.34rem 0.4rem; border-radius: 5px; right: 0; top: 0;">
                    <svg viewBox="0 0 24 24" height="24" width="24" fill="none" color="#ffffff" xmlns="http://www.w3.org/2000/svg">
                        <g stroke-width="0"></g>
                        <g id="" stroke-linecap="round" stroke-linejoin="round"></g>
                        <g id="">
                            <path d="M6 12H18M12 6V18" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
                        </g>
                    </svg>
                </button>
            `;
    }

    const addQuickReplyButton = `
        <button id="addQuickRepliesButton" class="btn btn-outline-success mb-2">Add Quick Replies button</button>
        `;

    const copyButton = `
        <button id="copyButton" type="button" class="btn btn-outline-success">Add Copy button</button>
        `;

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

    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"] = callIcon;
            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>
        `
    }

    function copyText() {

    }

    function onAddWebsiteOptionChange(e) {
        const domParser = new DOMParser();

        const value = e.currentTarget.value;

        const currentElement = e.currentTarget;

        const dataTargetID = currentElement.closest(".add-button-container-item").querySelector(".deleteButton").getAttribute("data-target");

        const buttonContainer = document.querySelector("#add-button-container");

        const parentElement = currentElement.closest(".add-button-container-item");

        const inputToBeReplaced = parentElement.querySelector(".addWebsiteButtonTextInput").parentElement;

        const inputValueToBeInserted = value === "url" ? "Visit" : "Call";

        const currentPreviewElement = document.getElementById(dataTargetID);

        currentPreviewElement.querySelector(".addWebsiteButtonText").textContent = inputValueToBeInserted;

        currentPreviewElement.querySelector("svg").remove();

        const URLPhoneContainer = parentElement.querySelector(".addWebsiteButtonURLAndPhoneContainer");

        if (value === "url") {
            const URLInputHTML = domParser.parseFromString(getAddWebsiteButtonURLElements("www.xyz.com"), "text/html").body.innerHTML;

            $(URLPhoneContainer).html(URLInputHTML);

            $(inputToBeReplaced).replaceWith(getAddWebsiteButtonInput(inputValueToBeInserted));

            const redirectIconHTML = domParser.parseFromString(redirectIcon, "text/html").body.firstChild;

            currentPreviewElement.prepend(redirectIconHTML);
        } else if (value === "phone") {
            const phoneInputHTML = domParser.parseFromString(getAddWebsiteButtonPhoneInput("1234567890"), "text/html").body.innerHTML;

            $(URLPhoneContainer).html(phoneInputHTML);

            $(inputToBeReplaced).replaceWith(getAddWebsiteButtonInput(inputValueToBeInserted));

            const callIconHTML = domParser.parseFromString(callIcon, "text/html").body.firstChild;

            currentPreviewElement.prepend(callIconHTML);
        }

        getURLPhoneSelectDetails(true);
    }

    function handleInputCharacterCount(event, dataTargetAttributeName, previewButtonTextClass, characterCountClass) {
        const value = event.currentTarget.value;

        const inputElement = event.currentTarget;

        const button = inputElement.parentElement.nextElementSibling;

        const textContentId = button.getAttribute(dataTargetAttributeName);

        const targettedVisitURL = document.getElementById(textContentId);
        targettedVisitURL.querySelector(`.${previewButtonTextClass}`).textContent = value;

        const characterCount = inputElement.parentElement.querySelector(`.${characterCountClass}`);

        characterCount.textContent = value.length;
    }

    function onAddWebsiteButtonTextChange(e) {
        handleInputCharacterCount(e, "data-target", "addWebsiteButtonText", "addWebsiteButtonTextCharacters");
    }

    function onCopyButtonTextChange(e) {
        handleInputCharacterCount(e, "data-target", "copyButtonText", "copyButtonInputTextCharacters");
    }

    function onQuickReplyButtonTextChange(e) {
        handleInputCharacterCount(e, "data-target", "quickReplyButtonText", "quickReplyInputCharacters");
    }

    function changePreviewData(event, dataTargetAttributeName, containerClassName, previewDataAttribute, characterCountClass) {
        const value = event.currentTarget.value;

        const inputElement = event.currentTarget;

        const addButtonContainerItem = inputElement.closest(`.${containerClassName}`);

        const deleteButton = addButtonContainerItem.querySelector(".deleteButton");

        const textContentId = deleteButton.getAttribute(dataTargetAttributeName);

        const targettedVisitURL = document.getElementById(textContentId);

        targettedVisitURL.parentElement.setAttribute(previewDataAttribute, value);

        const characterCount = inputElement.nextElementSibling.querySelector(`.${characterCountClass}`);

        characterCount.textContent = value.length;
    }

    function onCopyButtonCodeToCopyChange(e) {
        changePreviewData(e, "data-target", "copy-button-container-item", "preview-data", "copyButtonCodeToCopyCharacters");
    }

    function onAddWebsiteButtonURLChange(e) {
        changePreviewData(e, "data-target", "add-button-container-item", "preview-data", "addWebsiteButtonURLCharacters");
    }

    function removeSpecificElement(event) {
        const targetId = event.currentTarget.getAttribute("data-target");
        const targettedVisitURL = document.getElementById(targetId);
        targettedVisitURL.remove();
    }

    function deleteWebsiteButton(e) {
        if ($("#add-button-container").children(".add-button-container-item").length === 3) {
            $("#add-button-container").append(getPlusButton("url"));
        }
        $(this).closest(".add-button-container-item").remove();

        removeSpecificElement(e);

        if ($("#add-button-container").children().length < 1 + 1) {
            $("#addVisitWebsiteButtonPlus").remove();
            $("#addWebsiteCallButtonContainer").html(addVisitWebsiteButton);

            $("#addWebsiteCallButton").off("click", addWebsiteCallButtonListener);
            $("#addWebsiteCallButton").on("click", addWebsiteCallButtonListener);
        }

        getURLPhoneSelectDetails(true);
    }

    function deleteCopyButton(e) {
        $(this).closest(".copy-button-container-item").remove();

        removeSpecificElement(e)

        if ($("#copy-button-container").children().length < 1 + 1) {

            $("#copyButtonContainer").html(copyButton);

            $("#copyButton").off("click", addCopyButtonListener)
            $("#copyButton").on("click", addCopyButtonListener)
        }
    }

    function deleteQuickRepliesButton(e) {
        if ($("#quick-reply-button-container").children(".quick-reply-button-container-item").length === 3) {
            $("#quick-reply-button-container").append(getPlusButton("quickReply"));
        }

        $(this).closest(".quick-reply-button-container-item").remove();

        removeSpecificElement(e);

        if ($("#quick-reply-button-container").children().length < 1 + 1) {
            $("#addQuickReplyButtonPlus").remove()

            $("#quickRepliesButtonContainer").html(addQuickReplyButton);

            $("#addQuickRepliesButton").off("click", addQuickRepliesButtonListener)
            $("#addQuickRepliesButton").on("click", addQuickRepliesButtonListener)
        }
    }

    function addWebsiteCallButtonListener() {
        const URLAndPhoneCount = getURLPhoneSelectDetails();

        const idAndDataTargetAttribute = `button-${Date.now()}`;
        const defaultURL = "www.xyz.com";

        if ($("#add-button-container").children().length === 0) {
            $("#addWebsiteCallButton").remove()
            $("#add-button-container").append(getPlusButton("url"));
        }

        if ($("#add-button-container").children().length === 2 + 1) {
            $("#addVisitWebsiteButtonPlus").remove();
        }

        if ($("#add-button-container").children().length < 3 + 1) {
            if (URLAndPhoneCount.url >= 2) {
                $("#add-button-container").append(getAddWebsiteButtonContent(idAndDataTargetAttribute, "Call", "1234567890", "phone"));

                $("#preview-visit-website-container").append(getPreviewContent(idAndDataTargetAttribute, "1234567890", "phone"));
            } else {
                $("#add-button-container").append(getAddWebsiteButtonContent(idAndDataTargetAttribute, "Visit", defaultURL, "url"));

                $("#preview-visit-website-container").append(getPreviewContent(idAndDataTargetAttribute, defaultURL, "url"));
            }

            $(".deleteWebsiteCallButton").off("click", deleteWebsiteButton);

            $(".deleteWebsiteCallButton").on("click", deleteWebsiteButton);
        }

        getURLPhoneSelectDetails(true);
    }

    function addCopyButtonListener() {
        const idAndDataTargetAttribute = `button-${Date.now()}`;

        if ($("#copy-button-container").children().length === 0) {
            $("#copyButton").remove()
        }

        if ($("#copy-button-container").children().length < 1) {
            $("#copy-button-container").append(getCopyButtonItem(idAndDataTargetAttribute, "Copy offer code"));
            $("#copy-button-preview-container").append(getPreviewContent(idAndDataTargetAttribute, "", "copy"));

            $(".deleteCopyButton").off("click", deleteCopyButton);

            $(".deleteCopyButton").on("click", deleteCopyButton);
        }
    }

    function addQuickRepliesButtonListener() {
        const idAndDataTargetAttribute = `button-${Date.now()}`;

        if ($("#quick-reply-button-container").children().length === 0) {
            $("#addQuickRepliesButton").remove()
            $("#quick-reply-button-container").append(getPlusButton("quickReply"));
        }

        if ($("#quick-reply-button-container").children().length === 2 + 1) {
            $("#addQuickReplyButtonPlus").remove();
        }

        if ($("#quick-reply-button-container").children().length < 3 + 1) {
            $("#quick-reply-button-container").append(getQuickReplyButtonItem(idAndDataTargetAttribute, "Quick reply"));

            $("#quick-reply-button-preview-container").append(getPreviewContent(idAndDataTargetAttribute, "", "quickReply"));

            $(".deleteQuickRepliesButton").off("click", deleteQuickRepliesButton);

            $(".deleteQuickRepliesButton").on("click", deleteQuickRepliesButton);
        }
    }

    $("#addWebsiteCallButton").on("click", addWebsiteCallButtonListener);

    $("#addQuickRepliesButton").on("click", addQuickRepliesButtonListener);

    $("#copyButton").on("click", addCopyButtonListener);

    // Selecting the default marketing template as standard
    document.getElementById("standard").classList.add('selected');

    function initializeQuillEditor(idx) {
        const quillCarouselEditor = new Quill(`#quill-carousel-card-editor-${idx}`, {
            modules: {
                toolbar: `#carousel-toolbar-${idx}`
            },
            placeholder: 'Template Message...',
            theme: 'snow'
        });

        quillCarouselEditor.on('text-change', function(delta, oldDelta, source) {
            const htmlContent = quillCarouselEditor.root.innerHTML;
            const plainText = quillCarouselEditor.getText();

            let slide_id = $('.slider-card.carousel-card-selected').attr('id')
            if (slide_id) {
                const slide_text_container = $(`[data-slider-id="${slide_id}"]`).children().last().children().first();
                slide_text_container.text(plainText);
            }
            // console.log("HTML:", htmlContent);
            // console.log("Plain Text:", plainText);
        });

        const qParams = new URLSearchParams(window.location.search);

        const my_template = qParams.get("my-template");

        if (my_template && my_template === "yes") {
            $("#addNewTemplate").click();
        }
    }

    $(document).ready(function() {
        const swiperPrevBtn = document.querySelector('.swiper-button-prev');
        const swiperNextBtn = document.querySelector('.swiper-button-next');
        const dragAndDropCon = document.querySelector('.drag-and-drop-container');
        const carouselConDiv = document.querySelector("#carousel-container > div");

        // PREV BUTTON
        swiperPrevBtn.addEventListener('click', () => {
            let currentIdx = swiper.activeIndex;

            $(`.slider-card-num-${currentIdx}`).click();

            if (currentIdx === 0) {
                swiperPrevBtn.style.display = "none";
            } else {
                swiperPrevBtn.style.display = "flex";
            }

            swiperNextBtn.style.display = "flex";
        });


        // NEXT BUTTON
        swiperNextBtn.addEventListener('click', () => {
            const carouselItemConLen = document.getElementById("carousel-item-container").children.length;

            let currentIdx = swiper.activeIndex;
            $(`.slider-card-num-${currentIdx}`).click();

            if (currentIdx === carouselItemConLen - 1) {
                swiperNextBtn.style.display = "none";
            } else {
                swiperNextBtn.style.display = "flex";
            }

            swiperPrevBtn.style.display = "flex";
        });

        dragAndDropCon.addEventListener('click', () => {
            const carouselItemsCount = document.getElementById("carousel-item-container").children.length;

            for (let i = 0; i < carouselItemsCount; i++) {
                const sliderCard = document.querySelector(`.slider-card-num-${i}`);
                if (!sliderCard) continue;

                if (i == carouselItemsCount - 1) {
                    swiperNextBtn.style.display = "none";
                } else {
                    swiperNextBtn.style.display = "flex";
                }

                if (i == 0) {
                    swiperPrevBtn.style.display = "none";
                } else {
                    swiperPrevBtn.style.display = "flex";
                }

                sliderCard.addEventListener('click', () => {
                    if (i === 0) {
                        swiperPrevBtn.style.display = "none";
                    } else {
                        swiperPrevBtn.style.display = "flex";
                    }

                    if (i === carouselItemsCount - 1) {
                        swiperNextBtn.style.display = "none";
                    } else {
                        swiperNextBtn.style.display = "flex";
                    }
                });
            }

        });
    });
</script>

<script>
    let addNewTemplate = document.getElementById("addNewTemplate");
    let allTemplates = document.getElementById("allTemplates");
    let createTemplate = document.getElementById("createTemplate");
    let previewMessageFooterTextDiv = document.getElementById("preview-message-footer-text");
    let previewMessageFooterInput = document.getElementById("previewMessageFooterInput");
    let previewMessageBodyText = document.getElementById("preview-message-body-text");
    let addWebsiteCallButton = document.getElementById("addWebsiteCallButton");

    function addWebsiteCallButtonFn() {

    }

    function navigateToTemplateList() {
        createTemplate.classList.add("d-none"); // Hide template creation div
        createTemplate.classList.remove("createTemplate-fade-in"); // remove fade-in effect from template creation div
        createTemplate.classList.remove("createTemplate-show"); // remove fade-in effect from template creation div

        allTemplates.classList.remove("d-none"); // Show div of template list
        allTemplates.classList.add("createTemplate-fade-in"); // Add fade-in effect

        setTimeout(() => {
            allTemplates.classList.add("createTemplate-show");
        }, 10); // Small delay to allow transition        
    }

    function navigateToMyTemplates() {
        allTemplates.classList.add("d-none"); // Hide template list div
        allTemplates.classList.remove("createTemplate-fade-in"); // remove fade-in effect from template list div
        allTemplates.classList.remove("createTemplate-show"); // remove fade-in effect from template list div

        createTemplate.classList.remove("d-none"); // Make visible template creation div
        createTemplate.classList.add("createTemplate-fade-in"); // Add fade-in effect

        setTimeout(() => {
            createTemplate.classList.add("createTemplate-show");
        }, 10); // Small delay to allow transition
        const carouselConDiv = document.querySelector("#carousel-container > div");

        if (!carouselConDiv.classList.contains('swiper')) {
            carouselConDiv.classList.add('swiper');
        }

        edit_template = {
            edit: false,
            template_id: ''
        }
    }

    addNewTemplate.addEventListener("click", navigateToMyTemplates);

    // let debounceTimeout;

    previewMessageFooterInput.addEventListener("keyup", function(e) {
        const categoryValue = $("#category").val();

        if (categoryValue === "authentication") {
            e.currentTarget.setAttribute("readonly", "true");
            return;
        } else {
            e.currentTarget.removeAttribute("readonly");
        }
        // let footerValue = this.value;
        let footerValue = e.currentTarget.value;
        previewMessageFooterTextDiv.innerHTML = footerValue;
    });

    addWebsiteCallButton.addEventListener("click", addWebsiteCallButtonFn);
</script>


<script>
    document.addEventListener("DOMContentLoaded", function() {
        quill.root.dataset.placeholder = "Type your message body here...";
        quill.on("text-change", function() {
            const categoryValue = $("#category").val();

            if (categoryValue === "authentication") {
                quill.root.innerHTML = `{{1}} is your verification code.`;
                return;
            }

            // const richTextValue = quill.getText();
            const richTextValue = quill.root.innerHTML;

            if (richTextValue != "<p><br></p>") {
                previewMessageBodyText.innerHTML = richTextValue;
            } else {
                previewMessageBodyText.innerHTML = "";
            }

            insertSpanInPreviewMessage(richTextValue);

            showSampleContent(richTextValue);
        });

        showSampleContent();

        const carouselBtn = document.getElementById('carousel');
        const standardBtn = document.getElementById('standard');


        function clearStandardData() {
            const addWebCallBtnCon = document.getElementById('addWebsiteCallButtonContainer');
            const addBtnCon = document.getElementById('add-button-container'); //url buttons

            const coupenCon = document.getElementById('copy-button-container'); //coupen options container
            const copyBtnCon = document.getElementById('copyButtonContainer');

            const quickReplyLinksCon = document.getElementById('quick-reply-button-container');
            const quickReplyBtnCon = document.getElementById('quickRepliesButtonContainer');

            const broadcastTitlePreviewType = document.getElementById("broadcast-title-preview-type");
            const broadcastTitleRadioInputType = document.getElementById("broadcast-title-radio-input-type");
            const broadCastTitleRadioBtn = document.querySelector(".first-broadcast-checkbox");

            const broadcastTitleCon = document.querySelector('#broadcast-title-container');

            addBtnCon.innerHTML = "";
            coupenCon.innerHTML = "";
            quickReplyLinksCon.innerHTML = "";
            broadcastTitleRadioInputType.innerHTML = "";
            broadcastTitlePreviewType.innerHTML = "";
            broadcastTitleCon.innerHTML = "";
            document.getElementById('previewMessageFooterInput').value = "Powered by watify.io";
            broadCastTitleRadioBtn.checked = true;
            addWebCallBtnCon.innerHTML = addVisitWebsiteButton;
            document.getElementById('addWebsiteCallButton')?.addEventListener('click', addWebsiteCallButtonListener);

            copyBtnCon.innerHTML = copyButton;
            document.getElementById("copyButton")?.addEventListener('click', addCopyButtonListener);

            quickReplyBtnCon.innerHTML = addQuickReplyButton;
            document.getElementById("addQuickRepliesButton")?.addEventListener('click', addQuickRepliesButtonListener);

            //This will remove all links in message 
            document.getElementById('preview-visit-website-container').innerHTML = "";
            document.getElementById('copy-button-preview-container').innerHTML = "";
            document.getElementById('quick-reply-button-preview-container').innerHTML = "";
        }

        function clearCarouselData() {
            const swiperWrapper = document.querySelector('.swiper-wrapper');
            const carouselItemCon = document.getElementById('carousel-item-container');
            const editCarouselSecCon = document.getElementById('edit-carousel-section-container');
            const sliderCardLen = document.querySelectorAll(".slider-card").length;

            swiperWrapper.innerHTML = "";
            carouselItemCon.innerHTML = "";
            editCarouselSecCon.innerHTML = "";

            $("#carousel-card-length").html(0);
        }
        carouselBtn.addEventListener('click', clearStandardData);
        standardBtn.addEventListener('click', clearCarouselData);
    });
</script>

<script src="./JS/insertTemplate.js"></script>

<!-- ---------------------------------------------------------------------------------------------------------------------------------------------------- -->

<script>
    $(document).ready(function() {
        // Fetch languages
        $.ajax({
            url: 'https://app.watify.io/server/fetch_languages.php?type=language',
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    const select = $('#language');
                    select.empty().append('<option value="">Select Language</option>');
                    response.languages.forEach(function(lang) {
                        select.append($('<option>').val(lang.id).text(lang.name));
                    });
                } else {
                    console.error('❌ Error loading languages:', response.message);
                }
            },
            error: function(xhr, status, error) {
                console.error('❌ AJAX Error (language):', error);
            }
        });

        // Fetch categories
        $.ajax({
            url: 'https://app.watify.io/server/fetch_languages.php?type=category',
            method: 'GET',
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    const dropdown = $('#category');
                    dropdown.empty().append('<option value="">Select Category</option>');
                    response.categories.forEach(function(item) {
                        dropdown.append($('<option>').val(item.id).text(item.name));
                    });
                } else {
                    console.error('❌ Error loading categories:', response.message);
                }
            },
            error: function() {
                console.error('❌ Failed to load categories.');
            }
        });
    });
</script>

<!-- Creation of Data Table, edit, delete of data of templates  -->
<script>
    var edit_template = {
        edit: false,
        template_id: ''
    };

    function loadTable(columnIndex = 1, where = null, extrawhere = null, sort_by_createdAt = false) {

        let dataTableInstance = $('#all_message_templates').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: 'get_data_from_server/all_message_templates?template_data=1',
                type: "GET",
                data: {
                    all_leads_where_clause: where,
                    extrawhere: extrawhere,
                    sort_by_createdAt
                }
            },
            columns: columns,
            colReorder: true,
            fixedHeader: {
                header: true,
                headerOffset: 0
            },
            keys: true,
            responsive: false,
            pageLength: 10,
            drawCallback: function(settings) {
                // console.log(settings.json.query);
            }
        });

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

        return dataTableInstance;
    }
    document.querySelectorAll('.status_dropdown .form-check-label').forEach(label => {
        label.addEventListener('click', function(e) {
            e.stopPropagation();
        });
    });
    document.addEventListener('DOMContentLoaded', () => {
        if ($.fn.DataTable.isDataTable('#all_message_templates')) {
            $('#all_message_templates').DataTable().destroy();
            $('#all_message_templates').empty();
        }

        columns = [{
                data: 'id',
                orderable: false
            },
            {
                data: 'template_name'
            },
            {
                data: 'template_category'
            },
            {
                data: 'status',
                orderable: false
            },
            {
                data: 'template_language'
            },
            {
                data: 'updated_at'
            },
            {
                data: 'actions',
                orderable: false
            }
        ];

        const dataTableInstance = loadTable(1, null, null);

        $('#custom_sort').change(function(e) {
            e.preventDefault();

            const sortColumn = e.currentTarget.value;
            let columnIndex = columns.findIndex(col => col.data === sortColumn); // Find column index
            if (columnIndex == 1) {
                dataTableInstance.order([columnIndex, 'desc']).draw();
            } else {
                loadTable(-1, null, null, true);
            }
        });

        function getCategory(val) {
            const cate = {
                authentication: '1',
                marketing: '2',
                utility: '3'
            };

            for (let key in cate) {
                if (key.includes(val)) {
                    return cate[key];
                }
            }

            return '';
        }

        function getLangauge(val) {
            const lang = {
                english: '1',
                hindi: '2',
                spanish: '3',
                french: '4',
                german: '5',
                chinese: '6',
                japanese: '7',
                korean: '8',
                russian: '9',
                arabic: '10',
                portuguese: '11',
                bengali: '12',
                italian: '13',
                urdu: '14',
                turkish: '15'
            };

            // Loop through keys to find partial match
            for (let key in lang) {
                if (key.includes(val)) {
                    return lang[key]; // return the matched key (e.g., 'english')
                }
            }

            return ''; // No match found
        }

        const searchIcon = document.getElementById('searchIcon');

        searchIcon.addEventListener('click', () => {
            const searchInput = document.getElementById('searchInput');
            const searchVal = searchInput.value.trim().toLowerCase(); // Trim & lowercase for safety

            if (searchVal === '') {
                loadTable(); // Case 4: input is empty
                return;
            }

            const category = getCategory(searchVal);
            const language = getLangauge(searchVal); // Keep your original spelling if used elsewhere
            const sortColumn = $("#custom_sort").val();
            let columnIndex = columns.findIndex(col => col.data === sortColumn); // Find column index

            if (category !== '') {
                // Case 1: Matches category
                let query = `(template_category LIKE '%${category}%')`;
                loadTable(columnIndex, query);
            } else if (language !== '') {
                // Case 2: Matches language
                let query = `(template_language LIKE '%${language}%')`;
                loadTable(columnIndex, query);
            } else {
                // Case 3: Default to searching by template_name
                let query = `(template_name LIKE '%${searchVal}%' or updated_at LIKE '%${searchVal}%')`;
                loadTable(columnIndex, query);
            }
        });



        const searchInput = document.getElementById('searchInput');
        searchInput.addEventListener('keyup', (e) => {
            if (e.key == "Enter") {
                const searchVal = searchInput.value.trim().toLowerCase(); // Trim & lowercase for safety

                if (searchVal === '') {
                    loadTable(); // Case 4: input is empty
                    return;
                }

                const category = getCategory(searchVal);
                const language = getLangauge(searchVal); // Keep your original spelling if used elsewhere
                const sortColumn = $("#custom_sort").val();
                let columnIndex = columns.findIndex(col => col.data === sortColumn); // Find column index

                if (category !== '') {
                    // Case 1: Matches category
                    let query = `(template_category LIKE '%${category}%')`;
                    loadTable(columnIndex, query);
                } else if (language !== '') {
                    // Case 2: Matches language
                    let query = `(template_language LIKE '%${language}%')`;
                    loadTable(columnIndex, query);
                } else {
                    // Case 3: Default to searching by template_name
                    let query = `(template_name LIKE '%${searchVal}%' or updated_at LIKE '%${searchVal}%')`;
                    loadTable(columnIndex, query);
                }
            }
        });
        searchInput.addEventListener('input', (e) => {
            if (e.target.value === '') {
                loadTable();
            }
        });
    });
    document.addEventListener('click', (e) => {
        const target = e.target;

        if (!target.matches('#searchInput')) {
            const msgTemp = document.querySelector('#all_message_templates_filter label input[type="search"]');

            if (msgTemp && target.matches('#all_message_templates_filter label input[type="search"]')) {
                if ($('#searchInput').val() !== '') {
                    loadTable();
                }

                $('#searchInput').val('');

                // Delay to ensure the input is still focusable after DOM updates
                setTimeout(() => {
                    msgTemp.focus();
                }, 0);
            }
        } else if (target.matches('#searchInput')) {
            const msgTemp = document.querySelector('#all_message_templates_filter label input[type="search"]');

            if (msgTemp) {
                if (msgTemp.value != "") {
                    loadTable();
                }
                msgTemp.value = "";
            }
        }
    });
    // Function that reset template creation page to its initial state
    function clearPreviousTemplateData() {
        const template_name = document.getElementById('template-name');
        const template_category = document.getElementById('category');
        const template_language = document.getElementById('language');
        const template_footer = document.getElementById('previewMessageFooterInput');
        const add_btn_con_item = document.getElementById('add-button-container'); // visit-webiste btn
        const msgBox = document.querySelector('.standard-quill .ql-editor');

        template_name.value = "";
        template_category.value = "";
        template_language.value = "";
        template_footer.value = "Powered by watify.io";
        msgBox.innerHTML = "";
        msgBox.innerHTML = "<p><Br></p>";
        $("#broadcast-title-container").html("");

        if (add_btn_con_item.children.length > 1) {
            Array.from(add_btn_con_item.children).forEach((elm) => {
                if (elm.id != "addVisitWebsiteButtonPlus") {
                    elm.remove();
                }
            });
        }

        const bcast_title_type = document.querySelector(".first-broadcast-checkbox"); //first checkbox of broadcast tile which is none.
        const bcast_title_prev_type = document.querySelector('#broadcast-title-preview-type');
        const bcast_title_radio_input_type = document.querySelector('#broadcast-title-radio-input-type');

        bcast_title_type.checked = true;
        bcast_title_prev_type.innerHTML = "";
        bcast_title_radio_input_type.innerHTML = "";

        const template_type = document.querySelectorAll('.market-template');

        template_type.forEach((elm) => {
            if (elm.value.toLowerCase() == "standard") {
                elm.closest('.option-button').classList.add('selected');
                hideShowSections(
                    "show",
                    "template-footer-section",
                    "buttons-section",
                    "broadcast-title-section"
                );

                // sections to hide in standard template
                hideShowSections(
                    "hide",
                    "carousel-section",
                    "carousel-container"
                );
            } else {
                elm.closest('.option-button').classList.remove('selected');
            }
        });

        const visit_web_con = document.getElementById('add-button-container'); //a container of vist-websote buttons
        visit_web_con.innerHTML = "";
        $("#addWebsiteCallButtonContainer").html(addVisitWebsiteButton);
        $("#addWebsiteCallButton").off("click", addWebsiteCallButtonListener);
        $("#addWebsiteCallButton").on("click", addWebsiteCallButtonListener);
        $("#preview-visit-website-container").html("");

        const copy_offer_con = document.getElementById('copy-button-container'); //a container of copy offer code
        copy_offer_con.innerHTML = "";

        $("#copyButtonContainer").html(copyButton);
        document.getElementById("copyButton")?.addEventListener('click', addCopyButtonListener);
        $("#copy-button-preview-container").html("");
        // }

        const quick_reply_con = document.getElementById('quick-reply-button-container'); //a container of quick reply buttons
        quick_reply_con.innerHTML = "";

        $("#quickRepliesButtonContainer").html(addQuickReplyButton);
        document.getElementById("addQuickRepliesButton")?.addEventListener('click', addQuickRepliesButtonListener);
        $("#quick-reply-button-preview-container").html("");

        const swiperWrapper = document.querySelector('.swiper-wrapper');
        const carouselItemCon = document.getElementById('carousel-item-container');
        const editCarouselSecCon = document.getElementById('edit-carousel-section-container');
        const sliderCardLen = document.querySelectorAll(".slider-card").length;
        const carouselConDiv = document.querySelector("#carousel-container > div");

        swiperWrapper.innerHTML = "";
        carouselItemCon.innerHTML = "";
        editCarouselSecCon.innerHTML = "";
        carouselConDiv.classList.remove('swiper');
        $("#carousel-card-length").html(0);
    }

    function setBroadCastTitleChange(template_media_type, template_media_content) {
        if (template_media_type === "text") {
            $("#broadcast-title-preview-type").html("");

            $("#broadcast-title-radio-input-type").html(getBroadCastTitleInput(template_media_content, 60, "text", "onBroadCastTextInputChange"))

            $("#broadcast-title-container").html(`<h4 style="font-weight: 700; color: black;">${template_media_content}</h4>`);

        } else if (template_media_type === "image") {
            if (template_media_content) {
                $("#broadcast-title-preview-type").html(getBroadCastTitleImagePreview(template_media_content ? template_media_content : "images/dummy-image.webp", `broadcast-title-${template_media_type}-preview`))

                $("#broadcast-title-container").html(getBroadCastTitleImage(template_media_content ? template_media_content : "images/dummy-image.webp"));

                $("#image-reset-preview-button").css({
                    display: "inline"
                });
            } else {
                $("#broadcast-title-preview-type").html(getBroadCastTitleImagePreview("images/dummy-image.webp", `broadcast-title-${template_media_type}-preview`))

                $("#broadcast-title-container").html(getBroadCastTitleImage("images/dummy-image.webp"));

                $("#image-reset-preview-button").css({
                    display: "none"
                });
            }
            $("#broadcast-title-radio-input-type").html(getBroadCastTitleInput("", 2000, "image", "onBroadCastImageInputChange"));
        } else if (template_media_type === "video") {
            if (template_media_content) {
                $("#broadcast-title-preview-type").html(getBroadCastTitleVideoPreview(template_media_content, `broadcast-title-${template_media_type}-preview`))

                $("#broadcast-title-container").html(getBroadCastTitleVideo(template_media_content));

                $(`#video-reset-preview-button`).css({
                    display: "inline"
                });
            } else {
                $("#broadcast-title-preview-type").html(getBroadCastTitleImagePreview("images/video-dummy-image.svg", `broadcast-title-${template_media_type}-preview`, "video"))

                $("#broadcast-title-container").html(getBroadCastTitleImage("images/video-dummy-image.svg"));

                $(`#video-reset-preview-button`).css({
                    display: "none"
                });
            }
            $("#broadcast-title-radio-input-type").html(getBroadCastTitleInput("", 2000, "video", "onBroadCastVideoInputChange"));
        } else if (template_media_type === "document") {
            if (template_media_content) {
                $("#broadcast-title-preview-type").html(getBroadCastTitleDocumentPreview(template_media_content, `broadcast-title-${template_media_type}-preview`))

                $("#broadcast-title-container").html(getBroadCastTitleDocument(template_media_content));

                $(`#document-reset-preview-button`).css({
                    display: "inline"
                });

            } else {
                $("#broadcast-title-preview-type").html(getBroadCastTitleImagePreview("images/document-dummy-image.svg", `broadcast-title-${template_media_type}-preview`, "document"));

                $("#broadcast-title-container").html(getBroadCastTitleImage("images/document-dummy-image.svg"));


                $(`#document-reset-preview-button`).css({
                    display: "none"
                });
            }
            $("#broadcast-title-radio-input-type").html(getBroadCastTitleInput("", 2000, "document", "onBroadCastDocumentInputChange"));
        } else if (template_media_type === "") {
            $("#broadcast-title-preview-type").html("");

            $("#broadcast-title-radio-input-type").html("");

            $("#broadcast-title-container").html("");

        }

        const media_url_input = document.getElementById("image-url-input");

        if (!media_url_input) {
            return;
        }

        if (template_media_type !== "none" && template_media_type !== "text" && template_media_content) {
            media_url_input.disabled = true;
        } else {
            media_url_input.disabled = false;
        }
    }

    // Code to select and edit specific template
    document.querySelector('#all_message_templates_div').addEventListener('click', (e) => {
        const button = e.target.closest('.editMessageTemplate');

        if (button) {
            const template_id = button.getAttribute('data-message-template-id');

            let addNewTemplate = document.getElementById("addNewTemplate");
            let allTemplates = document.getElementById("allTemplates");
            let createTemplate = document.getElementById("createTemplate");

            let data = null;
            $.ajax({
                url: `get_data_from_server/all_message_templates?template_id=${template_id}&&find_template=1`,
                async: false,
                type: 'GET',
                contentType: 'application/json',
                success: function(res) {
                    data = res.template_data;
                },
                error: function(xhr, status, error) {
                    console.log(xhr);
                    console.log(error);
                    round_error_noti("Failed to open template, Try again later!");
                }
            })

            if (!data) {
                round_error_noti("Failed to open template, Try again!");
                return;
            }

            //Put data in front view 
            const template_name = document.getElementById('template-name');
            const template_category = document.getElementById('category');
            const template_language = document.getElementById('language');
            const template_type = document.querySelectorAll('.market-template');
            const template_footer = document.getElementById('previewMessageFooterInput');

            //Reset template name, category, language and footer 
            template_name.value = data.template_name;
            template_category.value = Number(data.template_category);
            template_language.value = Number(data.template_language);
            template_footer.value = data.template_footer;

            // Reset marketing template to standard
            template_type.forEach((elm) => {
                if (elm.value.toLowerCase() == data.template_type) {
                    elm.closest('.option-button').classList.add('selected');
                } else {
                    elm.closest('.option-button').classList.remove('selected');
                }
            });
            const inputs = document.querySelectorAll('.market-template');

            inputs.forEach((elm) => {
                if (elm.value.toLowerCase() === data.template_type.toLowerCase().trim()) {
                    elm.checked = true;
                } else {
                    elm.checked = false;
                }
            });
            const msgBox = document.querySelector('.standard-quill .ql-editor.ql-blank');
            if (msgBox) {
                const div = document.createElement('div');
                div.innerHTML = data.template_body || "<p></p>";

                msgBox.innerHTML = "";
                msgBox.append(...div.children);
            }

            if (data.template_type == "standard") {
                const template_media_type = document.querySelectorAll('.broadcast-checkbox');
                const template_media_preview = document.getElementById('broadcast-title-preview-type');
                const add_btn_con = document.getElementById('add-button-container');
                const quickReply_btn_con = document.getElementById('quick-reply-button-container');

                template_media_type.forEach((elm) => {
                    if (elm.value == data.template_media_type) {
                        elm.checked = true;
                    }
                });
                // Set image, video, document or text 
                setBroadCastTitleChange(data.template_media_type, data.template_media_content);

                // Set standard section visit website/call/quick reply buttions
                let visitWebBtnCount = 0,
                    quickRepCount = 0;
                if (data.buttons.length > 0) {
                    const add_visit_web_creation_btn_con = document.getElementById('addWebsiteCallButtonContainer');
                    add_visit_web_creation_btn_con.innerHTML = "";
                    let buttonCounter = 0;

                    data.buttons.forEach((btn) => {
                        const buttonId = `button-${Date.now()}-${buttonCounter++}`;

                        if (btn.button_type == "visit-website") {
                            const div = document.createElement('div');
                            div.innerHTML = getAddWebsiteButtonContent(buttonId, btn.text, btn.link, "url", btn.link_type);
                            div.querySelector(".deleteWebsiteCallButton").addEventListener('click', deleteWebsiteButton);
                            add_btn_con.appendChild(div.firstElementChild);
                            $("#preview-visit-website-container").append(getPreviewContent(buttonId, btn.link, "url"));
                            visitWebBtnCount++;
                        } else if (btn.button_type == "call-phone") {
                            const div = document.createElement('div');
                            div.innerHTML = getAddWebsiteButtonContent(buttonId, btn.text, btn.phone_number, "phone", btn.link_type);
                            div.querySelector(".deleteWebsiteCallButton").addEventListener('click', deleteWebsiteButton);
                            add_btn_con.appendChild(div.firstElementChild);
                            $("#preview-visit-website-container").append(getPreviewContent(buttonId, btn.phone_number, "phone"));
                        } else if (btn.button_type == "quick-reply") {
                            // remove button that create quick reply
                            document.getElementById("quickRepliesButtonContainer").innerHTML = "";
                            quickRepCount++;
                            // add quick reply button
                            const quick_div = document.createElement('div');
                            quick_div.innerHTML = getQuickReplyButtonItem(buttonId, btn.text);
                            quick_div.querySelector(".deleteQuickRepliesButton").addEventListener('click', deleteQuickRepliesButton);
                            quickReply_btn_con.appendChild(quick_div.firstElementChild);

                            // //add quickreplies in preview
                            $("#quick-reply-button-preview-container").append(getPreviewContent(buttonId, btn.text, "quickReply"));
                        }
                    });
                }

                if (visitWebBtnCount >= 1 && visitWebBtnCount < 3) {
                    $("#add-button-container").append(getPlusButton("url"));
                }
                if (quickRepCount >= 1 && quickRepCount < 3) {
                    const div = document.createElement('div');
                    div.innerHTML = getPlusButton();
                    quickReply_btn_con.appendChild(div.firstElementChild);
                }

                // Set copy offer code buttons
                if (data.copy_code) {
                    const copy_button_con = document.getElementById('copy-button-container');
                    const copy_btn_creation_btn_con = document.getElementById('copyButtonContainer');

                    const copyDiv = document.createElement('div');
                    const button_id = `button-${Date.now()}`;
                    copyDiv.innerHTML = getCopyButtonItem(button_id, data.copy_text, data.copy_code);
                    copyDiv.querySelector('.deleteCopyButton').addEventListener('click', deleteCopyButton);
                    copy_btn_creation_btn_con.innerHTML = "";
                    copy_button_con.appendChild(copyDiv.firstElementChild);
                    $("#copy-button-preview-container").append(getPreviewContent(button_id, data.copy_text, "copy"));

                }

            } else if (data.template_type == "carousel") {
                hideShowSections(
                    "hide",
                    "template-footer-section",
                    "buttons-section",
                    "broadcast-title-section"
                );
                if (document.querySelectorAll(".slider-card").length > 0) {
                    // sections to show in standard template
                    hideShowSections(
                        "show",
                        "carousel-section",
                        "carousel-container"
                    );
                } else {
                    hideShowSections(
                        "show",
                        "carousel-section"
                    );
                }

                const len = data.carousels.length;

                for (let i = 0; i < len; i++) {
                    addCarousel();
                }

                const slider_cards = document.querySelectorAll('.slider-card'); //Preview slides section
                const carousel_cards_media = document.querySelectorAll('.carousel-card-media'); //carousel card corresponding component
                const swiper_slides = document.querySelectorAll('.swiper-slide'); //slider cards
                const carousel_card_text_preview = document.querySelectorAll('.carousel-preview-visit-website-container');

                data.carousels.forEach((elm, idx) => {
                    // Set carousel images in carousel card, swiper card and carousel editable component
                    let media_content = null;

                    if (!elm.carousel_media_content) {
                        media_content = "https://app.watify.io/images/dummy-image.webp";
                        // if(elm.carousel_media_type == "image"){
                        // }else{
                        // }
                    } else {
                        media_content = elm.carousel_media_content;
                    }

                    const media_type = document.getElementById(`carousel-${elm.carousel_media_type}-${idx}`);
                    media_type.checked = true;

                    if (elm.carousel_media_content != null && elm.carousel_media_content != undefined) {
                        const image = `<div style="width: 24rem; height: 18rem; background: url(${media_content}); background-repeat: no-repeat; background-size: cover; background-position: center;"></div>`;
                        //input with radio tags
                        const media_input = document.querySelector(`#carousel-upload-media-${idx}`);
                        const swiper_slides_div = swiper_slides[idx].querySelector('div');

                        if (elm.carousel_media_type == "image") {
                            media_input.setAttribute("accept", ".webp");
                            carouselCardData[editContentId]["mediaType"] = "image";
                            carousel_cards_media[idx].innerHTML = image;
                            slider_cards[idx].style.background = `url(${media_content})`;
                            slider_cards[idx].style.backgroundRepeat = "no-repeat";
                            slider_cards[idx].style.backgroundPosition = "center";
                            slider_cards[idx].style.backgroundSize = "cover";

                            swiper_slides_div.style.background = `url(${media_content})`;
                            swiper_slides_div.style.backgroundRepeat = "no-repeat";
                            swiper_slides_div.style.backgroundPosition = "center";
                            swiper_slides_div.style.backgroundSize = "cover";

                        } else if (elm.carousel_media_type == "video") {
                            media_input.accept = ".mov,.mp4";
                            carouselCardData[editContentId]["mediaType"] = "video";

                            const caro_video = `<video class="rounded-3 w-50" src=${media_content} autoplay muted loop></video>`
                            carousel_cards_media[idx].innerHTML = caro_video;
                            const video = `<video style="width:100%; height: 100%; object-fit:cover;" class="rounded-3" src=${media_content} autoplay muted loop></video>`
                            slider_cards[idx].innerHTML = video;
                            swiper_slides_div.remove();
                            const divX = document.createElement('div');
                            divX.innerHTML = video;
                            swiper_slides[idx].insertAdjacentElement('afterbegin', divX.firstElementChild);
                        }
                    }

                    // set carousel editable component body content
                    const carousel_edit_comp = document.querySelector(`.edit-carousel-section-${idx}`);
                    const msgBox = carousel_edit_comp.querySelector('.ql-editor');
                    msgBox.innerHTML = elm.carousel_card_content;
                    // text in preview slider card
                    carousel_card_text_preview[idx].textContent = elm.carousel_card_content.replace(/<[^>]*>/g, '');

                    // carousel-add-web-btn --> btn to create
                    // carousel-add-btn --> add btn here

                    const carousel_btn = carousel_edit_comp.querySelector('.carousel-add-web-btn');
                    const carousel_btn_con = carousel_edit_comp.querySelector('.carousel-add-btn');

                    if (elm.buttons.length == 2) {
                        carousel_btn.style.display = "none";
                    }

                    elm.buttons.forEach((btnElm) => {
                        addEventToBtn(null, carousel_btn_con, btnElm, carousel_btn);
                    });
                    elm.buttons.forEach((btnElm) => {
                        const div = document.createElement('div');
                        div.innerHTML = getPreviewContent(btnElm.id, btnElm.link, btnElm?.button_type, btnElm.text);
                        document.querySelector(`.swiper-slide-${idx} .carousel-quick-reply-button-preview-container`).appendChild(div.firstElementChild);
                    });
                })
                if (data.carousels.length > 0) {
                    document.querySelector('.swiper-button-next').style.display = "none";
                }
                if (data.carousels.length > 1) {
                    document.querySelector('.swiper-button-prev').style.display = "flex";
                }
            }

            //function to navigate template creation or editable section
            navigateToMyTemplates();

            edit_template['edit'] = true;
            edit_template['template_id'] = data.id;
            edit_template['previous_template_media_content'] = data.template_media_content;
        }
    });

    // Delete template
    document.querySelector('#all_message_templates_div').addEventListener('click', (e) => {
        const delete_btn = e.target.closest('.deleteMessageTemplate');

        if (delete_btn) {
            const template_id = delete_btn.getAttribute('data-message-template-id');
            const template_type = delete_btn.getAttribute('data-template-type');
            console.log(template_id);
            console.log(template_type);

            $.ajax({
                url: `server/delete_template_from_list`,
                type: 'POST',
                data: JSON.stringify({
                    template_id: parseInt(template_id),
                    template_type: template_type
                }),
                contentType: 'application/json',
                success: function(res) {
                    // loadTable()
                    console.log(res);
                    round_success_noti(res["message"]);
                },
                error: function(xhr, status, error) {
                    console.log(xhr);
                    console.log(error);
                    round_error_noti("Failed to delete template!");
                }
            })
        }
    });
</script>

<?php require_once("./pin/footer.php"); ?>