<div class="modal fade" id="exportContactModal" tabindex="-1" role="dialog" aria-labelledby="exportContactModal" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" style="max-width: 100%;">
        <div class="modal-content" style="width: 1000px; margin:auto">
            <div class="modal-header">
                <h5 class="modal-title">Export Contacts</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">
                </button>
            </div>
            <div class="modal-body">
                <div class="mb-2">
                    <p>Choose the contacts you want to export</p>
                    <div class="d-flex gap-5">
                        <div class="form-check mb-2">
                            <input class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault1" value="all-contacts" onchange="filteredContactChanged(event)" checked>
                            <label class="form-check-label" for="flexRadioDefault1">
                                All contacts
                            </label>
                        </div>
                        <div class="form-check mb-2">
                            <input class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault2" value="filtered-contacts" onchange="filteredContactChanged(event)">
                            <label class="form-check-label" for="flexRadioDefault2">
                                Filtered contacts
                            </label>
                        </div>
                    </div>
                </div>
                <!-- filtered view modal -->
                <div class="container mb-2 d-none" id="showModal">
                    <div id="rowSection">
                        <div class="d-flex align-items-center gap-2">
                            <div class="form-group" style="width: 300px;">
                                <select id="filter1" class="form-select searchable_dropdown attribute-select">
                                    <option value="" disabled selected>Select an attribute</option>
                                </select>
                            </div>

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

                            <div class="form-group" style="width: 300px;">
                                <input type="text" class="form-control" placeholder="Value">
                            </div>

                            <button class="btn btn-outline-danger deleteContact" data-contact-id="11">
                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" class="actionBtn">
                                    <path d="M5 20a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8h2V6h-4V4a2 2 0 0 0-2-2H9a2 2 0 0 0-2 2v2H3v2h2zM9 4h6v2H9zM8 8h9v12H7V8z"></path>
                                    <path d="M9 10h2v8H9zm4 0h2v8h-2z"></path>
                                </svg>
                            </button>
                        </div>
                    </div>
                    <button class="btn btn-custom mt-2" onclick="addNewRow()">Add +</button>
                </div>
                <div>
                    <p>Timezone Settings</p>
                    <div class="">
                        <div class="form-check mb-2">
                            <input class="form-check-input" type="radio" name="timezoneSetting" id="flexRadioDefault3">
                            <label class="form-check-label" for="flexRadioDefault3">Use Customer Timezone</label>
                            <p style="font-size: smaller;">Apply timezone from account settings (GMT+0)</p>
                        </div>
                        <div class="form-check mb-2">
                            <input class="form-check-input" type="radio" name="timezoneSetting" id="flexRadioDefault4" checked>
                            <label class="form-check-label" for="flexRadioDefault4">Use UTC</label>
                            <p style="font-size: smaller;">Export all timestamps in UTC format</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-success" onclick="downloadCsv(event)" id="applyButton">Apply</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div>

<!-- Modals -->
<div class="modal fade bs-example-modal-xl" id="importContactModal" tabindex="-1" role="dialog" aria-labelledby="importContactModal" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Import Contacts via CSV</h5>
                <button type="button" class="btn-close uplaodCSVAgainBtn cancelImport" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div>
                    <div style="display: flex;align-items: flex-start;isolation: isolate;" class="mb-5">
                        <div style="position: relative;flex: 1 1 0%;padding-left: 8px;padding-right: 8px;">
                            <div style="display: flex;flex-direction: column;align-items: center;gap: 10px;font-weight: normal;">
                                <div class="step-head step-active">
                                    1
                                </div>
                                <div class="step-title step-title-active">
                                    Upload File
                                </div>
                            </div>
                        </div>

                        <div style="position: relative;flex: 1 1 0%;padding-left: 8px;padding-right: 8px;">
                            <div style="position: absolute;top: 26px;right: calc(50% + 20px);left: calc(-50% + 20px);flex: 1 1 auto;z-index: -1;">
                                <span style="display: block;border: 1px dashed rgb(35, 164, 85);"></span>
                            </div>
                            <div style="display: flex;flex-direction: column;align-items: center;gap: 10px;font-weight: normal;">
                                <div class="step-head">
                                    2
                                </div>
                                <div class="step-title">
                                    Map Columns
                                </div>
                            </div>
                        </div>

                        <div style="position: relative;flex: 1 1 0%;padding-left: 8px;padding-right: 8px;">
                            <div style="position: absolute;top: 26px;right: calc(50% + 20px);left: calc(-50% + 20px);flex: 1 1 auto;z-index: -1;">
                                <span style="display: block;border: 1px dashed rgb(35, 164, 85);"></span>
                            </div>
                            <div style="position: absolute;top: 26px;right: calc(50% + 20px);left: calc(-50% + 20px);flex: 1 1 auto;z-index: -1;"></div>
                            <div style="display: flex;flex-direction: column;align-items: center;gap: 10px;font-weight: normal;">
                                <div class="step-head">
                                    3
                                </div>
                                <div class="step-title">
                                    Confirm Import
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="" id="upload_step_first">
                        <h4 class="fw-bold">How to format the CSV?</h4>
                        <p class="mb-0">You can use Google Sheets or Microsoft Excel to generate a csv file (.csv or .csv utf-8). Your file must have phone number with country code, name. It can also have custom columns that can be imported to WATI as attributes. <a href="#">Download Sample CSV</a>.</p>

                        <div class="mt-4" id="uploadCSVBox">
                            <div class="upload-box" id="dropArea">
                                <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 24 24" style="fill: #00b363;">
                                    <path d="M13 19v-4h3l-4-5-4 5h3v4z"></path>
                                    <path d="M7 19h2v-2H7c-1.654 0-3-1.346-3-3 0-1.404 1.199-2.756 2.673-3.015l.581-.102.192-.558C8.149 8.274 9.895 7 12 7c2.757 0 5 2.243 5 5v1h1c1.103 0 2 .897 2 2s-.897 2-2 2h-3v2h3c2.206 0 4-1.794 4-4a4.01 4.01 0 0 0-3.056-3.888C18.507 7.67 15.56 5 12 5 9.244 5 6.85 6.611 5.757 9.15 3.609 9.792 2 11.82 2 14c0 2.757 2.243 5 5 5z"></path>
                                </svg>
                                <p class="mb-0"><span id="fileUploadText"><span class="fw-bold" style="color: #00b363;">Browse files</span> Drag and drop your import file here</span></p>
                                <p style="font-size: smaller;">File format must be .csv</p>
                                <input type="file" id="fileInput" accept=".csv">
                            </div>

                            <!-- <p class="file-info" id="fileInfo"></p>
                            <p class="status-message" id="statusMessage"></p> -->
                        </div>

                        <div class="mt-4 d-none" id="uploadCSVBoxError">
                            <div class="upload-box-error">
                                <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 24 24" style="fill: rgb(255 0 0);transform: ;msFilter:;">
                                    <path d="M11.953 2C6.465 2 2 6.486 2 12s4.486 10 10 10 10-4.486 10-10S17.493 2 11.953 2zM12 20c-4.411 0-8-3.589-8-8s3.567-8 7.953-8C16.391 4 20 7.589 20 12s-3.589 8-8 8z"></path>
                                    <path d="M11 7h2v7h-2zm0 8h2v2h-2z"></path>
                                </svg>
                                <p class="mb-0">Uh oh! Something's wrong with the uploaded file. Please ensure:</p>
                                <div class="text-start mt-2 ms-4">
                                    <ul>
                                        <li>All required fields are present: Name, country code, phone number</li>
                                        <li>Attributes are optional</li>
                                    </ul>
                                </div>
                                <span class="fw-bold uplaodCSVAgainBtn" style="color: #00b363;">Upload again</span>
                            </div>
                        </div>

                        <div class="mt-4 d-none" id="uploadCSVLoadingBox">
                            <div class="upload-box-loading" style="justify-content: center;flex-direction: column;">
                                <div class="spinner-border text-dark m-2" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                <span class="fw-bold">Loading...</span>
                            </div>
                        </div>

                        <div class="mt-4 d-none" id="uploadCSVSuccess">
                            <div class="upload-box-success">
                                <div>
                                    <h5 class="mb-0" id="fileInfo">Contacts_Upload_Sample.csv</h5>
                                    <span class="mb-0" id="fileSize">120 Bytes</span>
                                    <p class="status-message d-none" id="statusMessage"></p>
                                </div>
                                <div class="d-flex justify-content-center align-items-center gap-3">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 24 24" style="fill: rgb(0 179 99);transform: ;msFilter:;">
                                        <path d="M12 2C6.486 2 2 6.486 2 12s4.486 10 10 10 10-4.486 10-10S17.514 2 12 2zm-1.999 14.413-3.713-3.705L7.7 11.292l2.299 2.295 5.294-5.294 1.414 1.414-6.706 6.706z"></path>
                                    </svg>
                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" style="fill: rgba(0, 0, 0, 1);cursor: pointer;" class="uplaodCSVAgainBtn">
                                        <path d="m16.192 6.344-4.243 4.242-4.242-4.242-1.414 1.414L10.535 12l-4.242 4.242 1.414 1.414 4.242-4.242 4.243 4.242 1.414-1.414L13.364 12l4.242-4.242z"></path>
                                    </svg>
                                </div>
                            </div>
                            <div class="mt-3 p-2">
                                <div class="form-check mb-2">
                                    <input class="form-check-input" type="radio" name="importActionType" value="update_records" id="flexRadioDefault5" checked>
                                    <label class="form-check-label" for="flexRadioDefault5">Update records</label>
                                    <p style="font-size: smaller;">Existing contacts with same numbers will be replaced with values from the upload file</p>
                                </div>
                                <div class="form-check mb-2">
                                    <input class="form-check-input" type="radio" name="importActionType" value="skip_records" id="flexRadioDefault6">
                                    <label class="form-check-label" for="flexRadioDefault6">Skip records</label>
                                    <p style="font-size: smaller;">Existing contacts with same numbers will be skipped</p>
                                </div>
                            </div>
                        </div>

                        <div class="d-flex justify-content-end align-items-center gap-2 mt-5">
                            <button class="btn btn-outline-dark cancelImport">Cancel</button>
                            <button class="btn btn-success" id="mapColumnsBtn" disabled>Map Columns</button>
                        </div>
                    </div>
                    <div class="d-none" id="upload_step_second">
                        <h4 class="fw-bold">Column Mapping</h4>
                        <p class="mb-0">Choose where you want to import your fields. Please note that "Name" and "Phone" is always required.</p>

                        <div class="d-flex justify-content-between mt-3">
                            <div class="w-50 px-2 py-1"><span>Column name in CSV</span></div>
                            <div class="w-50 px-2 py-1"><span>Column name in Watify.io</span></div>
                        </div>
                        <div class="column-map-main p-2" id="columnMapMain">

                        </div>
                        <div class="mt-3" id="importColumnsCount">
                            <span class="fw-bold"><span id="importedColumn"></span>/<span id="totalImportedColumn"></span> column will be imported</span>
                        </div>
                        <div class="mt-3 d-none" id="importColumnsWarning">
                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" style="fill: rgba(0, 0, 0, 1);transform: ;msFilter:;">
                                <path d="M11.953 2C6.465 2 2 6.486 2 12s4.486 10 10 10 10-4.486 10-10S17.493 2 11.953 2zM12 20c-4.411 0-8-3.589-8-8s3.567-8 7.953-8C16.391 4 20 7.589 20 12s-3.589 8-8 8z"></path>
                                <path d="M11 7h2v7h-2zm0 8h2v2h-2z"></path>
                            </svg>
                            You must map “Name” and “Phone” column
                        </div>
                        <div class="d-flex justify-content-end align-items-center gap-2 mt-5">
                            <button class="btn btn-outline-dark" id="backImport">Back</button>
                            <button class="btn btn-success" id="confirmImport">Confirm Import</button>
                        </div>
                    </div>
                    <div class="d-none" id="upload_step_third">
                        <h4 class="fw-bold">Review upload</h4>
                        <div>
                            <p class="mb-2 d-flex align-items-center gap-2"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" style="fill: #00b363;">
                                    <path d="M12 2C6.486 2 2 6.486 2 12s4.486 10 10 10 10-4.486 10-10S17.514 2 12 2zm-1.999 14.413-3.713-3.705L7.7 11.292l2.299 2.295 5.294-5.294 1.414 1.414-6.706 6.706z"></path>
                                </svg>Contacts will be imported from Contacts_Upload_Sample.csv</p>
                            <p class="mb-2 d-flex align-items-center gap-2"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" style="fill: #00b363;">
                                    <path d="M12 2C6.486 2 2 6.486 2 12s4.486 10 10 10 10-4.486 10-10S17.514 2 12 2zm-1.999 14.413-3.713-3.705L7.7 11.292l2.299 2.295 5.294-5.294 1.414 1.414-6.706 6.706z"></path>
                                </svg>7/7 columns will be imported</p>
                            <p class="mb-2 d-flex align-items-center gap-2"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" style="fill: #00b363;">
                                    <path d="M12 2C6.486 2 2 6.486 2 12s4.486 10 10 10 10-4.486 10-10S17.514 2 12 2zm-1.999 14.413-3.713-3.705L7.7 11.292l2.299 2.295 5.294-5.294 1.414 1.414-6.706 6.706z"></path>
                                </svg>4 Valid Contacts will be imported</p>
                        </div>
                        <div class="mt-3">
                            <table id="uploadedCSVData" class="table table-bordered dt-responsive table-responsive nowrap" style="width: 100%;">
                                <thead>

                                </thead>
                                <tbody>

                                </tbody>
                            </table>
                        </div>
                        <div class="mt-3">
                            <span class="fw-bold">No Invalid Contacts found!</span>
                        </div>
                        <div class="d-flex justify-content-end align-items-center gap-2 mt-5">
                            <button class="btn btn-outline-dark cancelImport">Cancel Import</button>
                            <button class="btn btn-success" id="proceedToImport">Proceed to Import</button>
                        </div>
                    </div>
                </div>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div>

<div class="modal fade" id="confirmDeleteContactAttribute" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="confirmDeleteContactAttribute" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5">Delete Attribute</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                Do you want to delete custom attribute?
                <input type="hidden" id="removeAttriId">
                <input type="hidden" id="removeAttriKey">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary confirmRemoveAttribute" data-remove-attri-type="all">All Contacts</button>
                <button type="button" class="btn btn-primary confirmRemoveAttribute" data-remove-attri-type="current">Current Contact</button>
            </div>
        </div>
    </div>
</div>
<!-- scrollable Modal for add user-->
<!-- Modal -->
<div class="modal fade" id="addUserModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalScrollableTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="exampleModalScrollableTitle">Add User</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form action="">
                    <div class="mb-3">
                        <label for="firstName" class="form-label">First name</label>
                        <input type="text" id="firstName" class="form-control" placeholder="First name">
                    </div>
                    <div class="mb-3">
                        <label for="lastName" class="form-label">Last name</label>
                        <input type="text" id="lastName" class="form-control" placeholder="Last name">
                    </div>
                    <div class="mb-3">
                        <label for="emailId" class="form-label">Email</label>
                        <input type="email" id="emailId" name="email" class="form-control" placeholder="Email">
                    </div>
                    <div class=" mb-3">
                        <div class="form-check">
                            <input type="checkbox" class="form-check-input" id="emailConfirmed">
                            <label class="form-check-label fw-bold" for="emailConfirmed">Email Confirmed</label>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label for="phoneNumber" class="form-label">Phone Number</label>
                        <input type="tel" id="phoneNumber" name="phone" class="form-control" placeholder="Enter phone number">
                    </div>
                    <div class=" mb-3">
                        <div class="form-check">
                            <input type="checkbox" class="form-check-input" id="phoneConfirmed">
                            <label class="form-check-label fw-bold" for="phoneConfirmed">Phone Confirmed</label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="selectRolesDropDown" class="form-label">Roles</label>
                        <select id="selectRolesDropDown" class="form-select" multiple data-placeholder="Select Roles">
                            <option value="broadcast_manager">Broadcast Manager</option>
                            <option value="template_manager">Template Manager</option>
                            <option value="contact_manager">Contact Manager</option>
                            <option value="operator">Operator</option>
                            <option value="developer">Developer</option>
                            <option value="dashboard_viewer">Dashboard Viewer</option>
                            <option value="billing_manager">Billing Manager</option>
                            <option value="automation_manager">Automation Manager</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
                <button id="saveUserButton" type="button" class="btn btn-primary">Save</button>
                <button id="updateUserButton" type="button" class="btn btn-primary">Update</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="addContactModal" tabindex="-1" role="dialog" aria-labelledby="addContactModal" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" style="max-width: 100%;">
        <div class="modal-content" style="width: 650px; margin:auto">
            <div class="modal-header">
                <h5 class="modal-title">Add Contacts</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">
                </button>
            </div>
            <div class="modal-body">
                <div class="mb-2">
                    <div class="d-flex gap-4 align-items-end">
                        <!-- Name Field -->
                        <div class="mb-2" style="width: 45%;">
                            <label class="form-label" for="addContactName">Name</label>
                            <input class="form-control" type="text" name="addContactName" id="addContactName" placeholder="Enter Name">
                        </div>

                        <!-- Phone Number Field -->
                        <div class="mb-2" style="width: 55%;">
                            <label class="form-label" for="addPhoneNumber">Phone Number</label>
                            <div class="d-flex gap-2">
                                <div style="width: 40%;">
                                    <select class="form-select" id="countryDropdown">
                                        <option value="">Country</option>
                                    </select>
                                </div>
                                <div style="width: 60%;">
                                    <input class="form-control" type="text" name="addPhoneNumber" id="addPhoneNumber" placeholder="Enter Phone Number">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div>
                    <p class="mb-2">Custom Attribute (Optional)</p>
                    <div class="container px-0 mb-2" id="ContactAttributeContainer">
                        <div class="d-flex align-items-center gap-2 ContactAttributeRow">
                            <div class="form-group" style="width: 300px;">
                                <select class="form-select searchable_dropdown attribute-select" id="ContactAttributeDropdown">
                                    <option value="" disabled selected>Select an attribute</option>
                                    <option value="attribute1">Attribute 1</option>
                                </select>
                            </div>
                            <div class="form-group" style="width: 300px;">
                                <input type="text" class="form-control" placeholder="Value" id="valueInput">
                            </div>
                            <button class="btn btn-outline-danger deleteContact" onclick="removeContactRow(this)">
                                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="actionBtn">
                                    <path d="M5 20a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8h2V6h-4V4a2 2 0 0 0-2-2H9a2 2 0 0 0-2 2v2H3v2h2zM9 4h6v2H9zM8 8h9v12H7V8z"></path>
                                    <path d="M9 10h2v8H9zm4 0h2v8h-2z"></path>
                                </svg>
                            </button>
                        </div>
                    </div>
                    <button class="btn btn-custom mt-2" onclick="addNewContactRow()">Add +</button>
                </div>

                <div class="modal-footer d-flex justify-content-end m-2">
                    <button type="button" class="btn btn-outline-dark" id="cancelButton">Cancel</button>
                    <button type="button" class="btn btn-success" id="saveToDataBase">Save</button>
                </div>

                <style>
                    .btn-custom {
                        padding: 2px 6px;
                        font-size: 12px;
                        width: 100px;
                        height: 30px;
                        line-height: normal;
                    }

                    .d-flex {
                        align-items: center;
                    }

                    .mb-2 {
                        margin-bottom: 10px;
                    }

                    .ContactAttributeRow .form-group {
                        flex: 1;
                        min-width: 200px;
                    }

                    .deleteContact {
                        padding: 4px 8px;
                        font-size: 14px;
                    }
                </style>
                <script>
                    $(document).ready(function() {
                        // Fetch attributes
                        $.ajax({
                            url: 'https://app.watify.io/server/fetch_attributes.php', // API Endpoint
                            type: 'GET',
                            dataType: 'json',
                            success: function(data) {
                                // Store the fetched attributes for later use when adding rows
                                window.attributes = data;

                                // Initialize the first dropdown with attributes
                                $('.attribute-select').each(function() {
                                    let dropdown = $(this);
                                    dropdown.empty().append('<option value="" disabled selected>Select an attribute</option>'); // Reset dropdown

                                    // Append new options
                                    $.each(data, function(index, attri_name) {
                                        dropdown.append(`<option value="${attri_name}">${attri_name}</option>`);
                                    });

                                    // Initialize Select2 (if used)
                                    if ($.fn.select2) {
                                        setTimeout(() => {
                                            dropdown.select2({
                                                theme: "bootstrap-5",
                                                width: '100%',
                                                placeholder: "Select an attribute",
                                                minimumInputLength: 0,
                                                dropdownParent: dropdown.parent()
                                            });
                                        }, 100);
                                    }
                                });
                            },
                            error: function(xhr, status, error) {
                                console.log("Error:", error);
                                alert("Failed to fetch attributes.");
                            }
                        });

                        // Fetch countries
                        loadCountries("countryDropdown");
                    });

                    // Fetch countries from API
                    async function loadCountries(ddId) {
                        const response = await fetch("https://restcountries.com/v3.1/all");
                        const countries = await response.json();

                        const countryDropdown = document.getElementById(ddId);
                        countryDropdown.innerHTML = '<option value="">Country</option>'; // Reset dropdown

                        // Sort countries alphabetically by name
                        countries.sort((a, b) => a.name.common.localeCompare(b.name.common));

                        countries.forEach(country => {
                            let root = country.idd?.root || ''; // Get root dialing code
                            let suffix = country.idd?.suffixes ? country.idd.suffixes[0] : ''; // Get first suffix if exists

                            // Ensure no duplicate `+` signs
                            let dialingCode = (root + suffix).replace(/\+\+/g, '+');

                            if (dialingCode) { // Only add countries with a valid dialing code
                                let option = document.createElement("option");
                                option.value = dialingCode;
                                option.textContent = `${country.name.common} (${dialingCode})`;
                                countryDropdown.appendChild(option);
                            }
                        });
                    }
                    // Add new row section for new contact
                    function addNewContactRow() {
                        let container = document.getElementById("ContactAttributeContainer");
                        let newRow = document.createElement("div");
                        newRow.classList.add("d-flex", "align-items-center", "gap-2", "mt-1", "ContactAttributeRow");
                        newRow.innerHTML = `
    <div class="form-group" style="width: 300px;">
        <select class="form-select searchable_dropdown attribute-select">
            <option value="" disabled selected>Select an attribute</option>
            <!-- Options will be populated dynamically here -->
        </select>
    </div>
    <div class="form-group" style="width: 300px;">
        <input type="text" class="form-control" placeholder="Value">
    </div>
    <button class="btn btn-outline-danger deleteContact" onclick="removeContactRow(this)">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" class="actionBtn">
            <path d="M5 20a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8h2V6h-4V4a2 2 0 0 0-2-2H9a2 2 0 0 0-2 2v2H3v2h2zM9 4h6v2H9zM8 8h9v12H7V8z"></path>
            <path d="M9 10h2v8H9zm4 0h2v8h-2z"></path>
        </svg>
    </button>
    `;
                        // Append new row to the container
                        container.appendChild(newRow);

                        // Populate the new dropdown with the fetched attributes
                        const newDropdown = newRow.querySelector('.attribute-select');
                        window.attributes.forEach(function(attri_name) {
                            const option = document.createElement("option");
                            option.value = attri_name;
                            option.textContent = attri_name;
                            newDropdown.appendChild(option);
                        });

                        // Re-initialize Select2 on new dropdown
                        if ($.fn.select2) {
                            setTimeout(() => {
                                $(newDropdown).select2({
                                    theme: "bootstrap-5",
                                    width: '100%',
                                    placeholder: "Select an attribute",
                                    minimumInputLength: 0,
                                    dropdownParent: $(newRow).find('.form-group').first()
                                });
                            }, 100);
                        }
                    }

                    // Remove row
                    function removeContactRow(button) {
                        button.parentElement.remove();
                    }

                    // get all values of contact
                    $(document).ready(function() {
                        $('#saveToDataBase').on('click', function() {
                            let contacts = [];

                            // Collect Name, Phone Number, and Country Code
                            let name = $('#addContactName').val().trim();
                            let phone = $('#addPhoneNumber').val().trim();
                            let countryCode = $('#countryDropdown').val();

                            if (!name || !phone || !countryCode) {
                                alert(countryCode);
                                return;
                            }

                            let contact = {
                                name: name,
                                countrycode: countryCode,
                                phone: phone
                            };

                            // Loop through each ContactAttributeRow and collect the selected attribute and value
                            $('#ContactAttributeContainer .ContactAttributeRow').each(function() {
                                let attri_name = $(this).find('.attribute-select').val();
                                let attri_value = $(this).find('input').val().trim();

                                if (attri_name && attri_value) {
                                    contact[attri_name] = attri_value; // Store attributes inside the contact object
                                }
                            });

                            contacts.push(contact);

                            // Final JSON structure
                            let requestData = {
                                importAction: "append", // Modify based on user selection
                                contacts: contacts
                            };

                            console.log("Sending data:", requestData);

                            // Disable button to prevent multiple submissions
                            $('#saveToDataBase').prop("disabled", true).text("Saving...");

                            // Send to backend using AJAX
                            $.ajax({
                                url: "https://app.watify.io/server/upload-contacts",
                                type: "POST",
                                contentType: "application/json",
                                data: JSON.stringify(requestData),
                                success: function(response) {
                                    $('#addContactModal').modal('hide');
                                    console.log(response);
                                    round_success_noti("Contact Saved successfully");
                                },
                                error: function(error) {
                                    round_error_noti("Failed to save contact");
                                },
                                complete: function() {
                                    $('#saveToDataBase').prop("disabled", false).text("Save");
                                }
                            });
                        });
                    });
                </script>