<?php require_once("./pin/header.php"); ?>
<?php require_once("./pin/navbar.php"); ?>
<?php require_once("./pin/sidebar.php"); ?>

<style>
    .upload-box {
        width: 100%;
        height: 150px;
        border: 1px dashed #00b363;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        background-color: white;
        cursor: pointer;
        transition: 0.3s;
        text-align: center;
        border-radius: 10px;
    } 

    .upload-box-error {
        width: 100%;
        height: 180px;
        border: 1px dashed #ff0000;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        cursor: pointer;
        transition: 0.3s;
        text-align: center;
        border-radius: 10px;
        background-color: #ffeded;
    }

    .upload-box-success,
    .upload-box-loading {
        width: 100%;
        height: 100px;
        border: 1px solid #060707;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: white;
        transition: 0.3s;
        border-radius: 10px;
        padding: 0px 20px;
    }

    .upload-box.highlight {
        border-color: #28a745;
        background-color: #e3fcef;
    }

    #fileInput {
        display: none;
    }

    .file-info {
        margin-top: 10px;
        font-size: 16px;
        font-weight: bold;
        color: #333;
    }

    .status-message {
        margin-top: 10px;
        font-weight: bold;
        color: green;
    }

    .step-head {
        display: flex;
        width: calc(3.5rem);
        height: calc(3.5rem);
        border: 1px solid rgb(102, 102, 102);
        border-radius: 50%;
        background-color: rgb(255, 255, 255);
        color: rgb(102, 102, 102);
        font-size: calc(1.42857rem);
        font-weight: normal;
        align-items: center;
        justify-content: center;
    }

    .step-active {
        background-color: #00b363;
        color: #fff;
        border: none;
    }

    .step-title {
        color: rgb(102, 102, 102);
        font-size: calc(1.07143rem);
        font-weight: normal;
        text-align: center;
    }

    .step-title-active {
        color: rgb(35, 164, 85);
        font-weight: bold;
    }

    .cnicsv {
        display: flex;
        flex-grow: 3;
        flex-basis: 44%;
        background: #f5f6fa;
        padding: 18px;
        border-radius: 5px;
        gap: 22px;
    }

    .cniwatify {
        position: relative;
        flex-grow: 3;
        flex-basis: 44%;
        /* padding: 18px; */
        /* border-radius: 5px; */
        gap: 10px;
    }

    .cnicorrect {
        display: flex;
        align-items: center;
        justify-content: center;
        flex-grow: 1;
        flex-basis: 10%;
    }

    .column-map-main {
        display: flex;
        flex-direction: column;
        gap: 20px;
        max-height: 500px;
        overflow: auto;
    }

    /* Webkit-based browsers (Chrome, Safari, Edge, Opera) */
    .column-map-main::-webkit-scrollbar,
    .attributes-menu::-webkit-scrollbar {
        width: 5px;
        /* Vertical scrollbar width */
        height: 5px;
        /* Horizontal scrollbar height */
    }

    .column-map-main::-webkit-scrollbar-track,
    .attributes-menu::-webkit-scrollbar-track {
        background: #f1f1f1;
        /* Track background */
        border-radius: 10px;
    }

    .column-map-main::-webkit-scrollbar-thumb,
    .attributes-menu::-webkit-scrollbar-thumb {
        background: #888;
        /* Scrollbar color */
        border-radius: 10px;
    }

    .column-map-main::-webkit-scrollbar-thumb:hover,
    .attributes-menu::-webkit-scrollbar-thumb:hover {
        background: #555;
        /* Darker color on hover */
    }

    /* Edge & IE (hides default scrollbar) */
    .column-map-main {
        -ms-overflow-style: none;
    }

    .column-map-main::-ms-scrollbar {
        display: none;
    }

    .select2-container {
        width: 100% !important;
        z-index: 9999 !important;
    }

    .search-attribute {
        padding: 18px;
        width: 100%;
        border: 1px solid #dfdfdf;
        border-radius: 5px;
    }

    .search-attribute:focus {
        /* border: none; */
        outline: none;
    }

    .attributes-menu {
        display: flex;
        gap: 16px;
        max-height: 200px;
        flex-direction: column;
        overflow: hidden auto;
    }

    .attributes-action-btn {
        display: flex;
        gap: 10px;
    }

    .attribute-add-section,
    .search-attributes-section {
        position: absolute;
        top: -1px;
        right: -1px;
        left: -1px;
        padding: 20px;
        border: 1px solid rgba(144, 161, 189, 0.32);
        border-radius: 4px;
        background: rgb(255, 255, 255);
        z-index: 1;
    }

    .selected-attribute {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 18px;
        border: 1px solid rgba(144, 161, 189, 0.32);
        border-radius: 5px;
        height: 100%;
    }

    .selected-property {
        font-size: 16px;
    }

    #importColumnsWarning {
        border: 1px solid #ffeaca;
        width: fit-content;
        padding: 5px 10px;
        background: #ffeaca;
        font-weight: bold;
    }

    .remove-attribute:hover {
        fill: #ff0000 !important;
        cursor: pointer;
    }

    .deletContact:hover svg,
    .editContact:hover svg {
        fill: #fff !important;
    }

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

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

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

    .deleteContact {
        fill: #F44336;
    }

    /* .dataTables_scrollHeadInner{
        width: 100% !important;
    } */

    /* #all_contacts {
        width: 100% !important;
        table-layout: fixed;
    } */
</style>

<div class="content-page">
    <div class="content">

        <!-- Start Content-->
        <div class="container-fluid">
            <div class="py-3 d-flex align-items-sm-center flex-sm-row flex-column">
                <div class="flex-grow-1">
                    <h2 class="fw-bold m-0">Contacts</h2>
                    <p class="m-0">Contact list stores the list of numbers that you've interacted with. You can even manually export or import contacts.</p>
                </div>
                <div>
                    <button class="btn btn-success" id="addNewTemplate" data-bs-toggle="modal" data-bs-target="#addContactModal">Add Contact</button>
                    <p class="mb-0 mt-3 fw-bold text-dark" id="contactsCount"></p>
                </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="name">Name</option>
                                <option value="created_at">Created Date</option>
                            </select>
                        </div>
                        <div>
                            <div class="input-group">
                                <input type="text" class="form-control" placeholder="Search Contact..." aria-label="Search Contact..." aria-describedby="basic-addon2" id="searchInput">
                                <span class="input-group-text" 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);transform: ;msFilter:;">
                                        <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="#exportContactModal"><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="#importContactModal"><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">
                                <table id="all_contacts" class="table table-borderless table-centered align-middle table-nowrap mb-0 w-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">Basic info</th>
                                            <th scope="col" class="cursor-pointer">Phone number</th>
                                            <!-- <th scope="col" class="cursor-pointer">Source</th> -->
                                            <th scope="col" class="cursor-pointer">Contact attributes</th>
                                            <th scope="col" class="cursor-pointer">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>

                                    </tbody>
                                </table><!-- end table -->
                            </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>
    let mappingObjects;
    let filteredObjects;

    document.addEventListener("DOMContentLoaded", function() {
        const dropArea = document.getElementById("dropArea");
        const fileInput = document.getElementById("fileInput");
        const fileInfo = document.getElementById("fileInfo");
        const fileSize = document.getElementById("fileSize");
        const statusMessage = document.getElementById("statusMessage");
        const uploadCSVBox = document.getElementById("uploadCSVBox");
        const uploadCSVBoxError = document.getElementById("uploadCSVBoxError");
        const uploadCSVAgainBtns = document.getElementsByClassName("uplaodCSVAgainBtn");
        const uploadCSVSuccess = document.getElementById("uploadCSVSuccess");
        const uploadCSVLoadingBox = document.getElementById("uploadCSVLoadingBox");
        const upload_step_first = document.getElementById("upload_step_first");
        const upload_step_second = document.getElementById("upload_step_second");
        const upload_step_third = document.getElementById("upload_step_third");
        const mapColumnsBtn = document.getElementById("mapColumnsBtn");
        const confirmImport = document.getElementById("confirmImport");
        const cancelImport = document.getElementsByClassName("cancelImport");
        const backImport = document.getElementById("backImport");

        // getContactAttributes();
        countContacts();

        Array.from(uploadCSVAgainBtns).forEach(btn => {
            btn.addEventListener("click", () => {
                fileInput.value = "";
                uploadCSVBoxError.classList.add("d-none");
                uploadCSVSuccess.classList.add("d-none");
                uploadCSVBox.classList.remove("d-none");
                $('#uploadedCSVData tbody').html("");
                $('#uploadedCSVData thead').html("");

            });
        });

        Array.from(cancelImport).forEach(btn => {
            btn.addEventListener("click", () => {
                $("#importContactModal").modal("hide");
                document.getElementById("columnMapMain").innerHTML = "";
                upload_step_first.classList.remove("d-none");
                upload_step_second.classList.add("d-none");
                upload_step_third.classList.add("d-none");
                fileInput.value = "";
                uploadCSVBoxError.classList.add("d-none");
                uploadCSVSuccess.classList.add("d-none");
                uploadCSVBox.classList.remove("d-none");
                document.getElementsByClassName("step-head")[1].classList.remove("step-active");
                document.getElementsByClassName("step-title")[1].classList.remove("step-title-active");
                document.getElementsByClassName("step-head")[2].classList.remove("step-active");
                document.getElementsByClassName("step-title")[2].classList.remove("step-title-active");
                $('#uploadedCSVData tbody').html("");
                $('#uploadedCSVData thead').html("");
            });
        });

        backImport.addEventListener("click", function() {
            upload_step_first.classList.remove("d-none");
            upload_step_second.classList.add("d-none");

            document.getElementsByClassName("step-head")[1].classList.remove("step-active");
            document.getElementsByClassName("step-title")[1].classList.remove("step-title-active");
        });

        ["dragenter", "dragover", "dragleave", "drop"].forEach(eventName => {
            dropArea.addEventListener(eventName, preventDefaults, false);
        });

        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }

        ["dragenter", "dragover"].forEach(eventName => {
            dropArea.addEventListener(eventName, () => {
                dropArea.classList.add("highlight");
                document.getElementById("fileUploadText").innerHTML = "Drop your file";
            });
        });

        ["dragleave", "drop"].forEach(eventName => {
            dropArea.addEventListener(eventName, () => {
                dropArea.classList.remove("highlight");
                document.getElementById("fileUploadText").innerHTML =
                    "<span class='fw-bold' style='color: #00b363;'>Browse files</span> Drag and drop your import file here";
            });
        });

        dropArea.addEventListener("drop", (e) => {
            let files = e.dataTransfer.files;
            handleFiles(files);
        });

        dropArea.addEventListener("click", () => fileInput.click());

        fileInput.addEventListener("change", () => handleFiles(fileInput.files));

        // function handleFiles(files) {
        //     const file = files[0];

        //     if (!file) return;

        //     if (file.type !== "text/csv") {
        //         // fileInfo.innerText = "Only CSV files are allowed!";
        //         // fileInfo.style.color = "red";

        //         uploadCSVBox.classList.add("d-none");
        //         uploadCSVBoxError.classList.remove("d-none");
        //         return;
        //     }

        //     const reader = new FileReader();
        //     reader.readAsText(file);
        //     reader.onload = function (event) {
        //         const csvContent = event.target.result;
        //         const rows = csvContent.split("\n").map(row => row.trim());

        //         if (rows.length === 0) {
        //             // fileInfo.innerText = "The CSV file is empty!";
        //             // fileInfo.style.color = "red";

        //             uploadCSVBox.classList.add("d-none");
        //             uploadCSVBoxError.classList.remove("d-none");
        //             return;
        //         }

        //         const headers = rows[0].split(",").map(header => header.trim().toLowerCase());

        //         const requiredHeaders = ["name", "countrycode", "phone"];
        //         const missingHeaders = requiredHeaders.filter(header => !headers.includes(header));

        //         if (missingHeaders.length > 0) {
        //             // fileInfo.innerText = `Missing columns: ${missingHeaders.join(", ")}`;
        //             // fileInfo.style.color = "red";
        //             uploadCSVBox.classList.add("d-none");
        //             uploadCSVBoxError.classList.remove("d-none");

        //             return;
        //         }

        //         // fileInfo.innerText = `${file.name}`;
        //         // fileInfo.style.color = "#333";

        //         uploadCSVBox.classList.add("d-none");
        //         uploadCSVLoadingBox.classList.remove("d-none");

        //         setTimeout(() => {
        //             mapColumnsBtn.removeAttribute("disabled");
        //             uploadCSVLoadingBox.classList.add("d-none");
        //             uploadCSVSuccess.classList.remove("d-none");
        //             fileInfo.innerText = `${file.name}`;
        //             fileSize.innerText = `${file.size} Bytes`;
        //         }, 1000);

        //         // uploadFile(file);
        //     };
        // }

        function handleFiles(files) {
            const file = files[0];

            if (!file) return;

            if (file.type !== "text/csv") {
                uploadCSVBox.classList.add("d-none");
                uploadCSVBoxError.classList.remove("d-none");
                return;
            }

            const reader = new FileReader();
            reader.readAsText(file);
            reader.onload = function(event) {
                const csvContent = event.target.result.trim();
                const rows = csvContent.split("\n").map(row => row.trim());

                if (rows.length === 0) {
                    uploadCSVBox.classList.add("d-none");
                    uploadCSVBoxError.classList.remove("d-none");
                    return;
                }

                const headers = rows[0].split(",").map(header => header.trim().toLowerCase());

                const requiredHeaders = ["name", "countrycode", "phone"];
                const missingHeaders = requiredHeaders.filter(header => !headers.includes(header));

                if (missingHeaders.length > 0) {
                    uploadCSVBox.classList.add("d-none");
                    uploadCSVBoxError.classList.remove("d-none");
                    return;
                }

                const dataObjects = rows.slice(1).map(row => {
                    const values = row.split(",").map(value => value.trim());
                    return Object.fromEntries(headers.map((key, i) => [key, values[i] || ""]));
                });

                // console.log("Parsed Data:", dataObjects);
                mappingObjects = dataObjects
                displayMapping(dataObjects);

                uploadCSVBox.classList.add("d-none");
                uploadCSVLoadingBox.classList.remove("d-none");

                setTimeout(() => {
                    mapColumnsBtn.removeAttribute("disabled");
                    uploadCSVLoadingBox.classList.add("d-none");
                    uploadCSVSuccess.classList.remove("d-none");
                    fileInfo.innerText = `${file.name}`;
                    fileSize.innerText = `${file.size} Bytes`;
                }, 100);
            };
        }

        // function uploadFile(file) {
        //     let formData = new FormData();
        //     formData.append("csvFile", file);

        //     fetch("server/upload-contacts", {
        //         method: "POST",
        //         body: formData
        //     })
        //     .then(response => response.text())
        //     .then(data => {
        //         // statusMessage.innerText = data;
        //         mapColumnsBtn.removeAttribute("disabled");
        //         uploadCSVLoadingBox.classList.add("d-none");
        //         uploadCSVSuccess.classList.remove("d-none");
        //         fileInfo.innerText = `${file.name}`;
        //         fileSize.innerText = `${file.size} Bytes`;
        //     })
        //     .catch(() => {
        //         statusMessage.innerText = "File upload failed!";
        //         statusMessage.style.color = "red";
        //     });
        // }

        mapColumnsBtn.addEventListener("click", function() {
            upload_step_first.classList.add("d-none");
            upload_step_second.classList.remove("d-none");
            document.getElementsByClassName("step-head")[1].classList.add("step-active");
            document.getElementsByClassName("step-title")[1].classList.add("step-title-active");
        });

        confirmImport.addEventListener("click", function() {
            let extractedObj = [];
            let elements = document.getElementsByClassName("selected-property");

            let data = Array.from(elements).map(el => el.innerText).filter(text => text != "Select Property");
            let csvColumn = Array.from(elements)
                .map(el => el.innerText !== "Select Property" ? el.getAttribute("data-csv-column") : null)
                .filter(value => value !== null);

            // Storing key-value pairs in extractedObj
            // data.forEach((key, index) => {
            //     extractedObj[key] = csvColumn[index]; // Assign CSV column as value
            // });

            // console.log(extractedObj);
            // Storing key-value pairs in extractedObj
            data.forEach((key, index) => {
                extractedObj[csvColumn[index]] = key; // Swap key-value order
            });

            // console.log("Extracted Object:", extractedObj);

            // Mapping extractedObj to modify keys in mappingObjects
            filteredObjects = mappingObjects.map(obj => {
                let newObj = {};
                Object.keys(obj).forEach(oldKey => {
                    if (extractedObj[oldKey] || extractedObj['countrycode']) { // Only include keys that exist in extractedObj
                        newObj[extractedObj[oldKey]] = obj[oldKey]; // Assign value to new key
                    }
                });

                if (obj.hasOwnProperty("countrycode")) {
                    newObj["countrycode"] = obj["countrycode"];
                }
                return newObj;
            });

            // console.log(mappingObjects);

            // console.log("Filtered Objects:", filteredObjects);

            // console.log(csvColumn);
            // console.log(data);

            // filteredObjects = mappingObjects.map((obj) => {
            //     let result = {};

            //     data.forEach((key) => {
            //         if (obj[key] !== undefined) { 
            //             result[key] = obj[key];
            //         }
            //     });

            //     return result;
            // });


            // console.log(filteredObjects);

            // const customizeHeaders = Object.keys(filteredObjects[0]);
            const headers = Object.keys(filteredObjects[0]);

            // console.log("customize header: " + customizeHeaders);

            const headerRow = $('<tr></tr>');
            headers.forEach(header => {
                headerRow.append(`<th>${header.charAt(0).toUpperCase() + header.slice(1)}</th>`);
            });
            $('#uploadedCSVData thead').append(headerRow);

            filteredObjects.forEach(obj => {
                const row = $('<tr></tr>');
                headers.forEach(header => {
                    row.append(`<td>${obj[header]}</td>`);
                });
                $('#uploadedCSVData tbody').append(row);
            });

            $('#uploadedCSVData').DataTable();

            upload_step_second.classList.add("d-none");
            upload_step_third.classList.remove("d-none");
            document.getElementsByClassName("step-head")[2].classList.add("step-active");
            document.getElementsByClassName("step-title")[2].classList.add("step-title-active");
        });
    });

    let searchAttribute = `
    <div class="search-attributes-section" id="searchAttributesSection">
        <input class="search-attribute" id="searchAttribute" type="text" placeholder="Search">
        <hr/>
        <div class="attributes-menu">

        </div>
        <hr/>
        <div class="attributes-action-btn">
            <div><button class="btn btn-outline-dark remove-attri">Do not import column</button></div>
            <div><button class="btn btn-success" id="createContactAttribute">Create New</button></div>
        </div>
    </div>
`;


    $(document).on("click", ".cniwatify", function(event) {
        getContactAttributes();

        $(".search-attributes-section").remove();
        $(this).append(searchAttribute);

        event.stopPropagation();
    });

    $(document).on("click", function() {
        $(".search-attributes-section").remove();
        $(".attribute-add-section").remove();
    });

    $(document).on("click", ".search-attributes-section, .attribute-add-section", function(event) {
        event.stopPropagation();
    });

    $(document).on("click", ".attri-name-selector", function(event) {
        let attriName = $(this).attr("data-attri-name");

        let parentRow = $(this).closest(".d-flex");

        parentRow.find(".selected-property").text(attriName).css("font-weight", "bold");

        parentRow.find(".cnicorrect").html(`
        <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" 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>
    `);

        let importedColumn = Number($("#importedColumn").text());

        importedColumn += 1;

        $("#importedColumn").text(importedColumn);

        let csvColumn = parentRow.find(".selected-property").data("csvColumn");

        if (csvColumn == "name" || csvColumn == "phone") {
            let csvNameColumn = $("[data-csv-column='name']").text();
            let csvPhoneColumn = $("[data-csv-column='phone']").text();
            if (csvNameColumn != "Select Property" && csvPhoneColumn != "Select Property") {
                $("#importColumnsWarning").addClass("d-none");
                document.getElementById("confirmImport").removeAttribute("disabled", true);
            }
        }

        // Add the new key to each object in the array
        // filteredObjects.forEach(obj => {
        //     obj[attriName] = "value"; // Dynamically add the new key-value pair to each object
        // });

        if ($(".search-attributes-section").length) {
            $(".search-attributes-section").remove();
        }
    });

    function displayMapping(dataObjects) {
        if (dataObjects.length === 0) {
            console.log("No data available");
            return;
        }

        // const keys = Object.keys(dataObjects[0]); // Extract keys from the first object
        const keys = Object.keys(dataObjects[0]).filter(key => key !== "countrycode"); // Exclude 'countrycode'
        const container = document.getElementById("columnMapMain"); // The parent element where divs will be added

        // console.log(keys.length);
        const totalImportedColumn = keys.length;
        let importedColumn = 0;
        let isAttriSelected = "";

        keys.forEach(key => {
            const capitalizedKey = key.charAt(0).toUpperCase() + key.slice(1); // Capitalize first letter
            const dataCSVColumn = key;
            let capitalizedValue = "";
            let attriName = "";
            let attriStyle = "";

            if (key == "name") {
                capitalizedValue = "Watify Test";
                attriName = "name";
                attriStyle = "style='font-weight:bold;'";
                importedColumn++;
                isAttriSelected = '<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" 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>';

            } else if (key == "phone") {
                capitalizedValue = "9897594302";
                attriName = "phone";
                attriStyle = "style='font-weight:bold;'";
                importedColumn++;
                isAttriSelected = '<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" 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>';

            } else if (key == "allowbroadcast") {
                capitalizedValue = "TRUE";
                attriName = "allowbroadcast";
                attriStyle = "style='font-weight:bold;'";
                importedColumn++;
                isAttriSelected = '<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" 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>';

            } else if (key == "allowsms") {
                capitalizedValue = "TRUE";
                attriName = "allowsms";
                attriStyle = "style='font-weight:bold;'";
                importedColumn++;
                isAttriSelected = '<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" 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>';

            } else {
                capitalizedValue = "value";
                attriName = "Select Property";
                isAttriSelected = '<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 24 24" style="fill: rgb(255 0 0);"><path d="M12 2C6.486 2 2 6.486 2 12s4.486 10 10 10 10-4.486 10-10S17.514 2 12 2zm4.207 12.793-1.414 1.414L12 13.414l-2.793 2.793-1.414-1.414L10.586 12 7.793 9.207l1.414-1.414L12 10.586l2.793-2.793 1.414 1.414L13.414 12l2.793 2.793z"></path></svg>';

            }

            const div = document.createElement("div");
            div.className = "d-flex justify-content-between";
            div.innerHTML = `
            <div class="cnicsv">
                <div class="fs-5 fw-500">${capitalizedKey}</div>
                <div class="fs-5" style="color: #9d9d9d;">${capitalizedValue}</div>
            </div>
            <div class="cnicorrect">
                ${isAttriSelected}
            </div>
            <div class="cniwatify">
                <div class="selected-attribute">
                    <div class="selected-property" data-csv-column='${dataCSVColumn}' ${attriStyle}>${attriName}</div>
                    <div>
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" style="fill: rgb(155 155 155);">
                            <path d="M16.293 9.293 12 13.586 7.707 9.293l-1.414 1.414L12 16.414l5.707-5.707z"></path>
                        </svg>
                    </div>
                </div>
            </div>
        `;
            container.appendChild(div);
        });

        document.getElementById("totalImportedColumn").innerHTML = totalImportedColumn;
        document.getElementById("importedColumn").innerHTML = importedColumn;
    }

    $(document).on("click", ".remove-attri", function(event) {
        let parentRow = $(this).closest(".d-flex");
        let importedColumn = Number($("#importedColumn").text());

        importedColumn -= 1;

        $("#importedColumn").text(importedColumn);

        parentRow.find(".selected-property").text("Select Property").removeAttr("style");
        let csvColumn = parentRow.find(".selected-property").data("csvColumn");

        if (csvColumn == "name" || csvColumn == "phone") {
            $("#importColumnsWarning").removeClass("d-none");
            document.getElementById("confirmImport").setAttribute("disabled", true);
        }

        parentRow.find(".cnicorrect").html(`
        <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 24 24" style="fill: rgb(255 0 0);"><path d="M12 2C6.486 2 2 6.486 2 12s4.486 10 10 10 10-4.486 10-10S17.514 2 12 2zm4.207 12.793-1.414 1.414L12 13.414l-2.793 2.793-1.414-1.414L10.586 12 7.793 9.207l1.414-1.414L12 10.586l2.793-2.793 1.414 1.414L13.414 12l2.793 2.793z"></path></svg>
    `);

        if ($(".search-attributes-section").length) {
            $(".search-attributes-section").remove();
        }
    });

    $(document).on("click", "#proceedToImport", function(event) {
        let importActionType = $("input[name='importActionType']:checked").val();

        // console.log(importActionType);
        // console.log(filteredObjects);

        // Include importActionType in the request payload
        let requestData = {
            importAction: importActionType,
            contacts: filteredObjects
        };

        $.ajax({
            url: "server/upload-contacts", // Replace with actual PHP file URL
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify(requestData), // Convert object to JSON format
            success: function(response) {
                document.getElementsByClassName("cancelImport")[0].click();
                countContacts();
                dataTableInstance.ajax.reload(null, false);
            },
            error: function(xhr, status, error) {
                console.error("Error:", error);
                alert("Failed to import data.");
            }
        });
    });

    async function getContactAttributes() {
        try {
            let response = await fetch('server/get-attributes');
            if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
            let data = await response.text();

            // console.log(data);

            const observer = new MutationObserver(() => {
                let element = document.getElementsByClassName('attributes-menu')[0];
                if (element) {
                    element.innerHTML = data;
                    observer.disconnect();
                }
            });

            observer.observe(document.body, {
                childList: true,
                subtree: true
            });

            let element = document.getElementsByClassName('attributes-menu')[0];
            if (element) {
                element.innerHTML = data;
                observer.disconnect();
            }

        } catch (error) {
            console.error('Error:', error);
        }
    }


    document.addEventListener('keyup', function(event) {
        let input = document.getElementById('searchAttribute');
        if (input && event.target === input) {
            getSearchedAttribute(input.value);
        }
    });


    async function getSearchedAttribute(search_word) {
        try {
            let response = await fetch(`server/get-attributes?search=${encodeURIComponent(search_word)}`);
            if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
            let data = await response.text();

            let element = document.getElementsByClassName('attributes-menu')[0];
            if (element) {
                element.innerHTML = data;
            }

        } catch (error) {
            console.error('Error:', error);
        }
    }

    $(document).on("click", "#createContactAttribute", function() {
        let newContactAttribute = `
        <div class="attribute-add-section">
            <div>
                <div style="font-size:16px;">Attribute Name</div>
                <hr/>
                <div>
                    <input type="text" class="form-control" id="newContactAttributeName" placeholder="Enter Name">
                </div>
            </div>
            <hr/>
            <div class="attributes-action-btn">
                <div><button class="btn btn-outline-dark remove-addAttri">Cancel</button></div>
                <div><button class="btn btn-success addContactAttribute">Create New</button></div>
            </div>
        </div>
    `;

        $(this).closest(".cniwatify").append(newContactAttribute);
        $(".search-attributes-section").remove();
    });

    $(document).on("click", ".remove-addAttri", function() {
        getContactAttributes();
        $(this).closest(".cniwatify").append(searchAttribute);
        $(".attribute-add-section").remove();
    });

    $(document).on("click", ".addContactAttribute", function() {
        let newContactAttributeName = $("#newContactAttributeName").val();
        let isAttriSelected = '<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" 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>';
        // console.log(newContactAttributeName);

        // Ensure the input field has a value
        if (!newContactAttributeName) {
            console.log("Input is empty!");
            return;
        }

        // Find the closest `.cniwatify` and then locate `.selected-property` inside it
        let selectedProperty = $(this).closest(".cniwatify").find(".selected-property");
        // console.log("Selected Property Found:", selectedProperty.length);

        if (selectedProperty.length > 0) {
            selectedProperty.html(newContactAttributeName);
            selectedProperty.css("font-weight", "bold");
            $(this).closest(".cniwatify").prev().html(isAttriSelected);
        } else {
            console.log("No .selected-property found.");
        }

        $(".attribute-add-section").remove();
        let importedColumn = document.getElementById("importedColumn");
        importedColumn.innerHTML = Number(importedColumn.innerHTML) + 1;
    });

    let dataTableInstance;
    $(document).ready(function() {
        if ($.fn.DataTable.isDataTable('#all_contacts')) {
            $('#all_contacts').DataTable().destroy(); // Properly destroy existing table
            $('#all_contacts').empty(); // Clear table content to avoid duplicate headers
        }

        function loadTable(where = null, extrawhere = null) {
            columns = [{
                    data: 'id'
                },
                {
                    data: 'name'
                },
                {
                    data: 'phone'
                },
                {
                    data: 'country_code'
                },
                {
                    data: 'source'
                },
                {
                    data: 'created_at',
                    visible: false
                },
            ];
            
            let sortColumn = $('#custom_sort').val();
            let columnIndex = columns.findIndex(col => col.data === sortColumn); // Find column index
            let dataTableInstance = $('#all_contacts').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_contacts',
                    type: "GET",
                    data: {
                        all_leads_where_clause: where,
                        extrawhere
                    }
                },
                columns: columns,
                order: [
                    [columnIndex, 'DESC']
                ],
                colReorder: true,
                fixedHeader: {
                    header: true,
                    headerOffset: 0
                },
                keys: true,
                responsive: false,
                pageLength: 25,
                drawCallback: function(settings) {
                    // console.log(settings.json.query);
                }
            });

            // Force column width adjustment after rendering
            dataTableInstance.on('init', function() {
                setTimeout(function() {
                    dataTableInstance.columns.adjust().draw();
                }, 500);
            });
        }

        loadTable();

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

        $("#countryDropdown").select2({
            placeholder: "Select an attribute",
            theme: "bootstrap-5",
            width: '50% !important',
            dropdownParent: $('#addContactModal'),
            minimumInputLength: 0
        }).on("select2:open", function() {
            setTimeout(() => {
                $('.select2-dropdown').css({
                    'width': '265px',
                    'min-width': '265px'
                });
            }, 10);
        }).on("select2:selecting", function() {
            setTimeout(() => {
                $('.select2-dropdown').css({
                    'width': '265px',
                    'min-width': '265px'
                });
            }, 10);
        });

        filterArray = [];
        $("#searchIcon").click(function(){
            if($("#searchInput").val()!=''){
                let contactSeraching = $("#searchInput").val();
                let contactSearchInput = `(name LIKE '%${contactSeraching}%' or phone LIKE '%${contactSeraching}%')`;
                filterArray = []; 
                filterArray.push(contactSearchInput);
            }

            if(filterArray.length > 0){
                console.log(filterArray);
                loadTable(filterArray);
            }else{
                loadTable();
            }
        })
    });

    $(document).on("click", ".deleteContactAttri", function() {
        let attriId = $(this).data("attriId");
        let attriKey = $(this).data("contactAttriName");

        $("#confirmDeleteContactAttribute").modal("show");

        $("#removeAttriId").val(attriId);
        $("#removeAttriKey").val(attriKey);
    })

    $(document).on("click", ".confirmRemoveAttribute", function() {
        let removeAttriId = $("#removeAttriId").val();
        let removeAttriKey = $("#removeAttriKey").val();

        let removeAttriType = $(this).data("removeAttriType");

        $.ajax({
            url: "server/delete-attribute",
            type: "POST",
            data: {
                removeAttri: 1,
                removeAttriId,
                removeAttriKey,
                removeAttriType
            },
            success: function(res) {
                // console.log(res);
                let resp = JSON.parse(res);

                if (resp.status == 200) {
                    $("#confirmDeleteContactAttribute").modal("hide");
                    dataTableInstance.ajax.reload(null, false);
                }
                // console.log(resp.message);
            }
        })

    });

    $(document).on("click", ".deletContact", function() {
        let contactId = $(this).data("contactId");

        if (confirm("Do you want to delete this contact?")) {
            $.ajax({
                url: "server/delete-attribute",
                type: "POST",
                data: {
                    deleteContact: 1,
                    contactId
                },
                success: function(res) {
                    // console.log(res);
                    let resp = JSON.parse(res);

                    if (resp.status == 200) {
                        $("#confirmDeleteContactAttribute").modal("hide");
                        dataTableInstance.ajax.reload(null, false);
                    }

                    countContacts();
                    // console.log(resp.message);
                }
            })
        }
    });

    async function countContacts() {
        try {
            let response = await fetch(`server/count-contacts`);
            if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
            let data = await response.text();

            let element = document.getElementById("contactsCount");
            if (element) {
                element.innerHTML = `(${data} in total)`;
            }

        } catch (error) {
            console.error('Error:', error);
        }
    }
</script>
<script>
    function downloadCsv() {
        let selectedValue = document.querySelector('input[name="flexRadioDefault"]:checked').value;
        if (selectedValue == "all-contacts") {
            window.location.href = "https://app.watify.io/server/export_all_contacts_csv.php";
        } else {
            let allRows = document.querySelectorAll("#rowSection .d-flex"); // Select all rows (existing + newly added)

            let collectedData = [];

            allRows.forEach(row => {
                let attribute = row.querySelector(".attribute-select")?.value || "N/A";
                let operation = row.querySelector(".operation-select")?.value || "N/A"; // Select the second dropdown
                let value = row.querySelector("input[type='text']")?.value || "N/A";

                collectedData.push({
                    attribute: attribute,
                    operation: operation,
                    value
                });
            });

            // console.log("Collected Data:", collectedData);
            window.location.href = `https://app.watify.io/server/export_all_contacts_csv.php?filter=${JSON.stringify(collectedData)}`;
        }
    }

    function filteredContactChanged(e) {
        const showModal = document.getElementById("showModal");

        if (e.currentTarget.checked && e.currentTarget.value === "filtered-contacts") {
            showModal.classList.remove('d-none'); // Show the modal when checked and value is "filtered-contacts"
        } else {
            showModal.classList.add('d-none'); // Hide the modal when unchecked or different value
        }
    }

    let old_data = [];

    function addNewRow() {
        const rowSection = document.getElementById("rowSection");
        const newRowHTML = `
        <div class="d-flex align-items-center gap-2 mt-2">
            <div class="form-group" style="width: 300px;">
                <select class="form-select attribute-select">
                <option value="" disabled selected>Select an attribute</option>
                    ${old_data.join('')}
                </select>
            </div>

            <div class="form-group" style="width: 300px;">
                <select class="form-select operation-select">
                <option value="" disabled selected>Operation</option>
                                    <option value="contains">Contains</option>
                                    <option value="does not contain">Does not contain</option>
                                    <option value="exists">Exists</option>
                                    <option value="does not exist">Does not exist</option>
                                    <option value="=">Equal</option>
                                    <option value="!=">Doesn't Equal</option>
                                    <option value=">">Greater Than</option>
                                    <option value="<">Less Than</option>
                                    <option value=">=">Greater Than or Equal To</option>
                                    <option value="<=">Less Than or Equal To</option>
                </select>
            </div>
            <div class="form-group" style="width: 300px;">
                <input type="text" class="form-control" placeholder="Value">
            </div>

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

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

        let newRow = rowSection.lastElementChild;

        // Get only the new dropdown
        let newAttributeDropdown = newRow.querySelector(".attribute-select");
        let newOperationDropdown = newRow.querySelector(".operation-select");

        // // Copy options from the existing dropdown
        // let existingOptions = $("#filter1").html(); // Get all options from the first dropdown

        // // Populate only the new dropdown
        // $(newAttributeDropdown).html(existingOptions);
        setTimeout(() => {
            $(newAttributeDropdown).select2({
                placeholder: "Select an attribute",
                theme: "bootstrap-5",
                width: '100%',
                dropdownParent: $('#exportContactModal'),
                minimumInputLength: 0

            });
            $(newOperationDropdown).select2({
                placeholder: "Select an operation",
                theme: "bootstrap-5",
                width: '100%',
                dropdownParent: $('#exportContactModal'),
                minimumInputLength: 0
            });
        }, 100);
    }

    $(document).on('click', '.deleteContact', function(e) {
        e.preventDefault();
        $(this).parent().remove();
    });

    $(document).ready(
        function() {
            $.ajax({
                url: 'https://app.watify.io/server/fetch_attributes.php', // Your API endpoint
                type: 'GET',
                dataType: 'json',
                success: function(data) {
                    $('#filter1').empty().append('<option value="" disabled selected></option>'); // Reset dropdown
                    // Append new options
                    $.each(data, function(index, attri_name) {
                        let optionHTML = `<option value="${attri_name}">${attri_name}</option>`; // Store as a string
                        $('#filter1').append(optionHTML);
                        old_data.push(optionHTML); // Push string, not an element
                    });

                    // Reinitialize Select2
                    setTimeout(()=>{
                        $('#filter1').select2({
                            theme: "bootstrap-5",
                            width: $(this).data('width') ? $(this).data('width') : $(this).hasClass('w-100') ? '100%' : 'style',
                            placeholder: "Select an attribute",
                            dropdownParent: $('#exportContactModal'),
                            minimumInputLength: 0
                        });
                    },100);

                    $('#filter1').trigger('change'); // Ensure Select2 updates
                },
                error: function(xhr, status, error) {
                    console.log("Error:", error);
                    alert("Failed to fetch attributes.");
                }
            });
        });
</script>

<?php require_once("./pin/modals.php"); ?>
<?php require_once("./pin/footer.php"); ?>
<script>
    $(document).ready(function() {
        setTimeout(()=>{
            $(".searchable_dropdown").select2({
                theme: "bootstrap-5",
                dropdownParent: $('#exportContactModal')
            });
        },100);
    });
</script>