﻿<!DOCTYPE html>
<html lang="ur">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title class="urdu">  PULSE </title>
    <!-- plugins:css -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
    <!--<link rel="stylesheet" href="vendors/iconfonts/font-awesome/css/all.min.css">-->
    <link rel="stylesheet" href="vendors/css/vendor.bundle.base.css">
    <link rel="stylesheet" href="vendors/css/vendor.bundle.addons.css">

    <!--<link rel="stylesheet" href="/css/bootstrap.css">
    <link rel="stylesheet" href="/css/slick.css" />
    <link rel="stylesheet" href="/css/slick-theme.css" />
    <link rel="stylesheet" href="/css/animate.min.css">
    <link rel="stylesheet" href="/css/styles.css">-->
 
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
    <!--  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/leaflet.draw.css" />
    <link rel="stylesheet" href="src/leaflet-ruler.css" />

    <link rel="stylesheet" href="src/leaflet-ruler.css" />

    <style>
       

        .newlist {
            border: 1px solid green;
            border-radius: 10%;
            font-weight: 100;
            font-size: 0.8125rem;
            padding: .2375rem .45rem;
            margin-bottom: .5rem;
        }
        /* Add your custom styles for pagination here */
        .pagination {
            display: inline-block;
        }

            .pagination a {
                color: forestgreen;
                border-radius: 50% !important;
                position: relative;
                display: block;
                font-size: 1rem !important;
                padding: 0.5rem 0.75rem !important;
                margin-left: -1px;
                margin: 0.25rem !important;
                line-height: 1.25;
                text-decoration: none;
            }

                .pagination a.active {
                    background-color: #4CAF50;
                    color: white;
                    text-decoration: none; /* Remove underline on hover */
                    border-radius: 50% !important;
                }

                .pagination a:hover:not(.active) {
                    background-color: darkslategrey;
                    color: greenyellow;
                    border-radius: 50% !important;
                    text-decoration: none; /* Remove underline on hover */
                }

        .page-link {
            background-color: forestgreen !important;
            color: white !important;
            border-radius: 0.5rem !important;
            text-decoration: none; /* Remove underline on hover */
            border: none !important;
        }

        .table-fixed thead {
            width: 100%;
        }

        .table-fixed tbody {
            height: 230px;
            overflow-y: auto;
            width: 100%;
        }

        .flex-container {
            display: flex;
            flex-wrap: nowrap;
            align-items: center; /* Center items vertically */
        }

            .flex-container > div {
                margin: 10px;
                line-height: 15px;
            }

        .collapsible {
            background-color: forestgreen;
            color: white;
            cursor: pointer;
            padding: 1px;
            width: 100%;
            border: 1px solid green;
            border-radius: 5px;
            text-align: right;
            outline: none;
            font-size: 0.8rem;
            margin: 3px 0px 5px 0px;
        }

        .content {
           margin: 1rem 1rem 1rem 1rem;
            display: none;
            overflow: auto;
            color: white;
            background-color: forestgreen;
            border-radius: 10px;
        }
        ul {
            font-size: 1rem !important;
            line-height: 1 !important;
        }
        li {
            font-size: 1rem !important;
            line-height: 1 !important;
        }
        table {
            width: 100%;
            border-collapse: collapse;
         
            text-align:center !important;

        }

        th, td {
            border: 1px solid forestgreen !important;
            padding: 2px;
        
        }

        th {
            background-color: forestgreen;
            border: 1px solid white;
            color: white;
        }
        tbody {
            max-height: 200px; /* Set a max height for the tbody */
            overflow-y: auto !important; /* Enable vertical scrolling for tbody */
        }
        .custom-tooltip {
            background-color: transparent;
            color: yellow;
            padding: 0px;
            border: none; /* Remove border */
            box-shadow: none; /* Remove box shadow */
            font-size: 1rem;
            font-weight: bold;
            text-align: center;
        }

        .polygon-label-new {
            background-color: red;
            color: white;
            border: none;
            padding: 1px;
            font-size: 12px;
            direction: center;
            /* Add more styles as needed */
        }
        .polygon-label-new2 {
            background:none;
            color: red;
            border: none;
            padding: 0px;
            font-size: 3px;
            /* Add more styles as needed */
        }
        .polygon-label-d {
            background-color: transparent;
            color: red;
            padding: 2px;
            border: none; /* Remove border */
            box-shadow: none; /* Remove box shadow */
            font-size: 1rem;
            font-weight: bold;
            text-align: center;
        }
        .polygon-label-t {
            background-color: transparent;
            color: yellow;
            padding: 2px;
            border: none; /* Remove border */
            box-shadow: none; /* Remove box shadow */
            font-size: 1rem;
            font-weight: bold;
            text-align: center;
        }
        .custom-circle-icon {
            text-align: center;
            color: #fff;
            /* Color of the circle */
        }

        .circle {
            width: 10px;
            /* Width of the circle */
            height: 10px;
            /* Height of the circle */
            background-color: rgb(99, 31, 22);
            /* Background color of the circle */
            border-radius: 50%;
            /* Make it a circle */
        }
        .floating-button {
           
            top: 5vh;
            left: 3em;
            background-color: darkred;
            color: #fff;
            border: none;
            padding: 15px 20px;
            font-size: 16px;
            border-radius: 20px;
            cursor: pointer;
            box-shadow: rgba(60,0,0, 0.2) 2px 5px 5px;
        }

            .floating-button:hover {
                background-color: indianred;
            }
        .floating-button2 {
            
            top: 5vh;
            left: 30vh;
            background-color: darkred;
            color: #fff;
            border: none;
            padding: 15px 20px;
            font-size: 16px;
            border-radius: 20px;
            cursor: pointer;
            box-shadow: rgba(60,0,0, 0.2) 2px 5px 5px;
        }

            .floating-button2:hover {
                background-color: indianred;
            }
        .visible {
            display: block;
            z-index: 9999;
        }

        .hidden {
            display: none;
        }

        .custom-popup {
            background-color: transparent;
            color: blue;
            padding: 0px;
            border: none; /* Remove border */
            box-shadow: none; /* Remove box shadow */
            font-size: 0.7rem;
            
            text-align: center;
        }

    </style>


    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js"></script>
 
    <!-- endinject -->
    <!-- plugin css for this page -->
    <!-- End plugin css for this page -->
    <!-- inject:css -->
    <link rel="stylesheet" href="/css/style.css">
    <!--  <link rel="stylesheet" href="/css/keyboard.css">-->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">

    <!-- DataTables CSS -->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.css">
    <!--  <link rel="stylesheet" href="/css/keyboard.css">-->
    <!-- endinject -->
    <link rel="shortcut icon" href="/images/favicon.ico" />

</head>
<body class="horizontal-menu ">
    <div class="container-scroller">
        <nav class="navbar horizontal-layout-navbar  navbar-expand-lg">
            <div class="text-center navbar-brand-wrapper d-flex align-items-center justify-content-start">
                <a class="navbar-brand brand-logo urdu" style="font-size: 2.5rem !important; color: white !important; letter-spacing: 0.5rem;" href="index.html">PULSE</a>
                <!--<a class="navbar-brand brand-logo-mini" href="../index.html"><img src="../images/PulseIcon/Asset 2favicon.png " alt="logo" /></a>-->


            </div>

        </nav>
        <div class="container-fluid">
            <div class="main-panel">



                <div class="urdu" style="margin: 1rem 1rem 0rem 1rem;">

                    <div class="col-md-12">

                        <form method="get" accept-charset="utf-8" id="searchForm">
                            <div class="search-filter" id="filtersPanel">
                                <div class="row form-group">
                                    <div class="col-sm-2 col-md-3">
                                        <select class="form-control " id="districtSelect" required="required">
                                            <option value="">District</option>
                                        </select>
                                    </div>

                                    <div class="col-sm-2 col-md-3">
                                        <select class="form-control  " id="tehsilSelect" required="required">
                                            <option value="">Tehsil</option>
                                        </select>
                                    </div>

                                    <div class="col-sm-2 col-md-3">
                                        <select class="form-control  " id="zoneSelect" required="required">
                                            <option value="">Zone</option>
                                        </select>
                                    </div>
                                    <div class="col-sm-2 col-md-3">
                                        <select class="form-control  " id="khewatSelect" required="required" disabled>
                                            <option value="">Khewat</option>
                                        </select>
                                        <span style="text-align:end !important; float:right !important; text-decoration-color:forestgreen !important" onclick="hideunhideadvSpanel()">Advance Search</span>
                                    </div>



                                </div>









                            </div>

                        </form>

                    </div>
                    <div class="col-md-12 hidden " id="advSpanel">
                        <div class="row form-group">

                            <div class="col-sm-4 col-md-4">
                                <input class="form-control  " id="plotid" placeholder="Search by Parcel Unique ID...." />
                            </div>
                            <div class="col-sm-2 col-md-2">
                                <button type="button" id="searchButton" onclick=" fetchDatabyParcelID()" class=" btn-sm" style="border:none !important;">
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                        <circle cx="11" cy="11" r="8" stroke="rebeccapurple"></circle>
                                        <line x1="21" y1="21" x2="16.65" y2="16.65" stroke="rebeccapurple"></line>

                                    </svg>

                                </button>

                            </div>
                            <div class="col-sm-4 col-md-4">
                                <input class="form-control  " id="cnicvalue" placeholder="Search by CNIC of Person...." disabled />
                            </div>
                            <div class="col-sm-2 col-md-2">
                                <button type="button" id="searchButton2" onclick=" fetchDatabyCNIC()" class=" btn-sm" style="border:none !important;">
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                        <circle cx="11" cy="11" r="8" stroke="rebeccapurple"></circle>
                                        <line x1="21" y1="21" x2="16.65" y2="16.65" stroke="rebeccapurple"></line>

                                    </svg>

                                </button>

                            </div>
                        </div>
                    </div>


                    <div class="col-md-12 hidden" id="parcelSpanel">

                        <div class="row">
                            <div class="col-md-3" style="text-align:center; box-shadow: 4px 4px 8px rgba(0, 0, 0, 0.2); ">
                                <h6 class="urdu" style="color: forestgreen;">Parcel Unique ID</h6>

                                <div id="parcelSpanelplotid" style="color: rebeccapurple;"></div>

                            </div>

                            <div class="col-md-3" style="text-align:center; box-shadow: 4px 4px 8px rgba(0, 0, 0, 0.2); ">
                                <h6 class="urdu" style="color: forestgreen;">Parcel Area</h6>

                                <div id="parcelSpanelarea" style="color: rebeccapurple;"></div>

                            </div>

                            <div class="col-md-3" style="text-align:center; box-shadow: 4px 4px 8px rgba(0, 0, 0, 0.2); ">
                                <h6 class="urdu" style="color: forestgreen;">Parcel Number</h6>

                                <div id="parcelSpanelparcelno" style="color: rebeccapurple;"></div>

                            </div>





                        </div>

                    </div>


                    <div class="row" style="height: 80vh;margin-top:1vh;">
                        <div class="col-md-12" id="mappanel">
                            <!--     <div id="map" style="height: 60vh;" hidden></div>-->
                            <div id="map" style="height: 80vh; border: 2px solid forestgreen; border-radius: 10px; box-shadow: 4px 4px 8px rgba(0, 0, 0, 0.2); "></div>

                        </div>


                        <div class="col-md-3  hidden" id="leftpanel" style="float: right !important; text-align:center; height: 80vh; overflow-x: auto; padding: 0px; border: 3px solid rebeccapurple; border-radius: 10px; box-shadow: 4px 4px 8px rgba(0, 0, 0, 0.2); ">
                            <h6 class="urdu" style="color: forestgreen;">Details for Parcel</h6><h4 id="selectedParcelNo" hidden></h4><h6 id="selectedParcelNoUnique" class="urdu" style="color: rebeccapurple"></h6>
                            <div id="parcel-container" style="font-size: 1rem !important; margin: 1rem 1rem 1rem 1rem; border: 2px solid forestgreen; min-height: 6%; display: block; background-color: white; color: rebeccapurple; ">

                            </div>
                            <h6 class="urdu" style="color: forestgreen;">Owners Details</h6>
                            <div id="persons-container" class="urdu" style="margin: 1rem 1rem 1rem 1rem; border: 2px solid forestgreen; overflow-y: auto; min-height: 20%; max-height: 60% "></div>
                            <div class="col-md-12">
                                <button type="button" id="initiateTransfer" onclick="" class=" auth-form-btn hidden " style="border: none !important;  border-radius: 20px; background-color: darkred; color: white; margin: 1rem 1rem 1rem 1rem ;">Click Here to Initiate Transfer(Taqseem)</button>
                            </div>

                        </div>
                        <div class="col-md-3  hidden" id="pdpanel" style="text-align:center; height: 80vh; overflow-x: auto; padding: 0px; border: 3px solid rebeccapurple; border-radius: 10px; box-shadow: 4px 4px 8px rgba(0, 0, 0, 0.2); ">


                        </div>
                        <div id="buttonpanel" class="hidden" style=" margin: 1rem 1rem 1rem 1rem ;">
                            <button id="splitButton" class="btn btn-outline-success">Finalize Split</button>
                            <button id="SaveNewParcels" class="btn btn-outline-danger hidden">Save New Parcels</button>
                            <button id="AddAttribToParcel" class="floating-button2 hidden">Initiate Members Allotment</button>


                        </div>









                    </div>
                </div>

                <footer class="footer" style="direction:ltr !important">
                    <div class="d-sm-flex justify-content-center justify-content-sm-between">
                        <span class="text-muted text-center text-sm-left d-block d-sm-inline-block">
                            PULSE, Copyright ©
                            <script>
                                document.write(new Date().getFullYear())
                            </script> All rights reserved.
                        </span>
                        <span class="float-none float-sm-right d-block mt-1 mt-sm-0 text-center">
                            Crafted By PULSE Software Development Team
                        </span>
                    </div>
                </footer>
            </div>
        </div>
    </div>



    <!-- Bootstrap loading Modal  -->
    <div class="modal fade" id="loadingModal" style="background-color:transparent" tabindex="-1" role="dialog" aria-labelledby="loadingModal" aria-hidden="true">
        <div class="modal-dialog" style="background-color:transparent" role="document">
            <div class="modal-content" style="background-color:transparent; border:hidden">
                <!--<div class="modal-header">-->
                <!-- <h5 class="modal-title" id="loadingModalLabel">Loading...</h5>-->
                <!--<button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>-->

                <div class="text-center">
                    <div class="spinner-grow text-success" style="width: 6rem; height: 6rem; margin-top:20rem" role="status">

                    </div>
                </div>

            </div>
        </div>
    </div>


    <!-- Leaflet JavaScript -->

    <script src="vendors/js/vendor.bundle.base.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="vendors/js/vendor.bundle.addons.js"></script>
    <script src="https://code.highcharts.com/highcharts.js"></script>
    <script src="https://code.highcharts.com/highcharts-3d.js"></script>
    <script src="https://code.highcharts.com/modules/cylinder.js"></script>
    <script src="https://code.highcharts.com/modules/drilldown.js"></script>
    <script src="https://code.highcharts.com/modules/data.js"></script>
    <script src="https://code.highcharts.com/modules/exporting.js"></script>
    <script src="https://code.highcharts.com/modules/export-data.js"></script>
    <script src="https://code.highcharts.com/modules/accessibility.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/min/dropzone.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
    <script src="js\customeJs\spotlight.bundle.js"></script>
    <!-- Include SweetAlert library -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdn.rawgit.com/mapbox/wellknown/master/wellknown.js"></script>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@turf/turf@6.5.0/turf.min.js"></script>


    <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/leaflet.draw.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/esri-leaflet/3.0.12/esri-leaflet.js"></script>



    <!-- DataTables JS -->
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.js"></script>

    <script src="js/off-canvas.js"></script>
    <script src="js/hoverable-collapse.js"></script>
    <script src="js/misc.js"></script>
    <script src="js/settings.js"></script>
    <script src="js/todolist.js"></script>
    <script src="js/form-validation.js"></script>
    <script src="js/customeJs/slick.js"></script>

    <script src="js/dashboard.js"></script>
    <script src="js/customeJs/datafile.js"></script>
    <script src="js/customeJs/main.js"></script>
    <script src="js/customeJs/common.js"></script>
    <script src="js/customeJs/custom.js"></script>

    <!-- Proj4js -->
    <script src="src/proj4.js"></script>
    <script src="src/proj4leaflet.js"></script>
    <script src="src/leaflet-ruler.js"></script>
    <script>
        // Function to read parameter from URL
        function getParameterByName(name) {
            var urlParams = new URLSearchParams(window.location.search);
            return urlParams.get(name);
        }

        // Read the search parameter from the URL
        var searchParam = getParameterByName('searchParam');


        // Perform the search or any other action based on the parameter
        if (searchParam) {
            // Set the input value to the searchParam value
            var plotIdInput = document.getElementById("plotid");
            plotIdInput.value = searchParam;

            // Call the fetchDatabyParcelID() function
            fetchDatabyParcelID();
        }
        var osmUrl = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}';
        //  var osmUrl = 'https://basemaps.arcgis.com/arcgis/rest/services/World_Basemap_v2/VectorTileServer';

        //    var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
        //     var osmAttrib = '&copy; <a href="http://openstreetmap.org/copyright">OpenStreetMap</a> contributors';
        var osm = L.tileLayer(osmUrl, { maxZoom: 30, attribution: "Pulse Mapping Service" });
        var geojsonLayer3 = L.featureGroup();
        var basePolygons = L.featureGroup();
        var drawnPolygons = L.featureGroup();

        var drawnLines = L.featureGroup();
        //  var geojsonLayer;

        var map = new L.Map('map', { center: new L.LatLng(52.505, -0.04), zoom: 18 });
        // Create layer control
        var layerControl = L.control.layers({
            'Base Map': osm
        }, {
            'Drawn Parcels': basePolygons
        }, {
            collapsed: true
        }).addTo(map);
        osm.addTo(map);
        drawnPolygons.addTo(map);
        drawnPolygons.setStyle({
            color: 'pink',  // Set your desired highlight color
            weight: 3,
            fillOpacity: 0.5
        });
        basePolygons.addTo(map);
        var optionsruler = {
            position: 'topright',         // Leaflet control position option
            circleMarker: {               // Leaflet circle marker options for points used in this plugin
                color: 'red',
                radius: 2
            },
            lineStyle: {                  // Leaflet polyline options for lines used in this plugin
                color: 'red',
                dashArray: '1,6'
            },
            lengthUnit: {                 // You can use custom length units. Default unit is kilometers.
                display: 'karam',              // This is the display value will be shown on the screen. Example: 'meters'
                decimal: 3,                 // Distance result will be fixed to this value.
                factor: (596.52),               // This value will be used to convert from kilometers. Example: 1000 (from kilometers to meters)
                label: 'Distance:'
            },
            angleUnit: {
                display: '&deg;',           // This is the display value will be shown on the screen. Example: 'Gradian'
                decimal: 2,                 // Bearing result will be fixed to this value.
                factor: null,                // This option is required to customize angle unit. Specify solid angle value for angle unit. Example: 400 (for gradian).
                label: 'Angle:'
            }
        };
        // Create a draggable marker
        //    L.marker([-73.99017333984375, 40.73207874849907], { draggable: true }).addTo(map);

        L.control.ruler(optionsruler).addTo(map);

        drawnLines.addTo(map);

        map.addControl(new L.Control.Draw({
            draw: {
                marker: false,
                circle: false,
                circlemarker: false,
                rectangle: false,
                polygon: false
            }
        }));
        // Set the maximum zoom level at which you want to display the Esri basemap
        var maxZoomToShowBasemap = 18;

        // Listen for the 'zoomend' event
        map.on('zoomend', function () {
            // Check the current zoom level
            var currentZoom = map.getZoom();

            // If the current zoom level is greater than the maximum allowed, hide the basemap
            if (currentZoom > maxZoomToShowBasemap) {
              //  map.removeLayer(osm);
            } else {
                // If the current zoom level is within the allowed range, make sure the basemap is added
                if (!map.hasLayer(osm)) {
                    osm.addTo(map);
                }
            }
        });



        //var geojsonLayer;

        //function loaddata(id){

        //    fetch('../api/GeoJSON/' + id)
        //    .then(response => response.json())
        //        .then(data => {

        //        // Iterate through each plot in the response
        //        data.forEach(plot => {
        //            // Convert WKT to GeoJSON
        //            console.log("I am here  ---------------",plot.shape);
        //            var wkt = wellknown.parse(plot.shape);
        //            console.log(wkt);

        //            // Add GeoJSON to the map
        //            geojsonLayer = L.geoJSON(wkt, {
        //                onEachFeature: function (feature, layer) {
        //                    // Optionally, add a popup to each feature
        //                    var properties = feature.properties;
        //                    // Optionally, add a popup to each feature
        //                    //                    var popupContent = Object.keys(plot).map(function (key) {
        //                    //                        return key + ": " + plot[key];
        //                    //                    }).join("<br>");
        //                    var popupContent = Object.keys(plot).map(function (key) {
        //                        return key + ": " + plot[key];

        //                    }).join("<br>");



        //                   // layer.bindPopup(popupContent);
        //                    layer.on('click', function (e) {
        //                        // Update the existingPolygon coordinates


        //                        // Update the existingPolygon coordinates

        //                       // fetchAndPopulatePersons(plot.plot_id);
        //                       // fetchAndPopulateParcel(plot.plot_id);
        //                        existingPolygon.geometry.coordinates[0] = [];
        //                        existingPolygon.geometry.coordinates[0] = e.target.feature.geometry.coordinates[0];

        //                     //   var container = document.getElementById('leftpanel');
        //                     //   var container2 = document.getElementById('mappanel');


        //                     //   container.style.display = 'block';


        //                   //     container2.classList.add("col-md-9");
        //                   //     container2.classList.remove("col-md-12");
        //                        console.log("Updated Ppolygons are are:");
        //                        console.log(existingPolygon.geometry.coordinates[0]);

        //                        // Create a new GeoJSON layer with the updated polygon
        //                        drawnPolygons.clearLayers();

        //                        var updatedPolygonLayer = L.geoJSON(existingPolygon).addTo(drawnPolygons);

        //                      //   toggleSelection(updatedPolygonLayer);

        //                        // Add the drawnPolygons layer group to the map
        //                      //  drawnPolygons.addTo(map);
        //                        console.log("updated are:");
        //                        console.log(existingPolygon.geometry.coordinates);

        //                        // Convert Leaflet polygon to Turf.js feature
        //                        var turfPolygon = turf.polygon(existingPolygon.geometry.coordinates);
        //                        // Calculate area using Turf.js
        //                        var area = turf.area(turfPolygon);
        //                        console.log("Area is: ", area);

        //                        existingPolygon.bindPopup(area)
        //                        // Fit the map to the bounds of the updated polygon layer
        //                        var bounds = updatedPolygonLayer.getBounds().pad(1);
        //                        map.fitBounds(bounds);
        //                    });
        //                }
        //            }).addTo(map);

        //           //  Fit the map to the bounds of the GeoJSON layer
        //           map.fitBounds(geojsonLayer.getBounds().pad(1));

        //        });
        //    })
        //    .catch(error => console.error('Error loading WKT geometries:', error));
        //}

        function PopulateParcelDataOnEditor(data) {

            console.log(data);
            data.forEach(parcel => {
                console.log(parcel);

                document.getElementById("parcelSpanelarea").innerHTML = sqmTOkmf(parcel.area_sqrft);
                document.getElementById("parcelSpanelplotid").innerHTML = parcel.parcel_unique_id;
                document.getElementById("parcelSpanelparcelno").innerHTML = parcel.parcel_no + "/" + parcel.parcel_sub_no;


            });

        }
        function updateParcelState(plotId, newState) {
            // Define the endpoint URL
            var apiUrl = '../api/GeoJSON/' + plotId + '/' + newState;

            // Create a new XMLHttpRequest object
            var xhr = new XMLHttpRequest();

            // Configure the request
            xhr.open('PUT', apiUrl, true);
            xhr.setRequestHeader('Content-Type', 'application/json');

            // Set up a callback function to handle the response
            xhr.onload = function () {
                if (xhr.status >= 200 && xhr.status < 300) {
                    // Request was successful
                    console.log('Parcel state updated successfully');
                    // You can perform further actions here if needed
                } else {
                    // Request failed
                    console.error('Failed to update parcel state');
                }
            };

            // Set up a callback function to handle network errors
            xhr.onerror = function () {
                console.error('Network error occurred');
            };

            // Send the request with the provided data
            xhr.send();
        }

        function intimateWithData(data) {
            console.log("starting intimating process.........");
            data.forEach(parcel => {
                // Create an object with the parcel data
                const requestData = {
                    PlotIdPoc: parcel.parcel_id,
                    PlotNo: parcel.parcel_no,
                    SubPlotNo: parcel.parcel_sub_no,
                    PlotUniqueId: parcel.parcel_unique_id,
                    TransferStatus: "Initiated",
                    FromPoc: 1
                };

                // Make an AJAX POST request to the specified endpoint
                // fetch('https://demo.pulse.gop.pk/api/Hspts/TransferInitiation', {
                fetch('https://demo.pulse.gop.pk/api/Hspts/TransferInitiation', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                })
                    .then(response => {
                        if (response.ok) {
                            // If the request was successful
                            console.log('Parcel transfer Initiated...:', parcel.PlotUniqueId);
                            updateParcelState(parcel.parcel_id, 1);
                            Swal.fire({
                                icon: 'success',
                                title: 'Success!',
                                text: 'Parcel transfer Initiated...',
                                timer: 5000, // Set the timer to 2000 milliseconds (2 seconds)
                                timerProgressBar: true, // Enable progress bar
                            }).then((result) => {
                                // Reload the page when the modal closes
                                location.reload();
                            });

                        }
                        else if (response.status === 409) {
                            // If the request was successful
                            console.log('Parcel already Initiated...:', parcel.PlotUniqueId);

                            Swal.fire({
                                icon: 'warning',
                                title: 'Already Initiated!',
                                text: 'Parcel Transfer process is already under process...',
                                timer: 5000, // Set the timer to 2000 milliseconds (2 seconds)
                                timerProgressBar: true, // Enable progress bar
                                showConfirmButton: false // Hide the confirm button
                            }).then((result) => {
                                // Reload the page when the modal closes
                               location.reload();
                            });



                        }
                        else {
                            // If there was an error, log the error message and show error notification
                            console.error('Failed to transfer parcel:', parcel.PlotUniqueId);
                            Swal.fire({
                                icon: 'error',
                                title: 'Error!',
                                text: 'Failed to Initiate transfer parcel: ' + parcel.PlotUniqueId
                            });
                        }
                    })
                    .catch(error => {
                        // Log any network errors and show error notification
                        console.error('Network error:', error);
                        Swal.fire({
                            icon: 'error',
                            title: 'Error!',
                            text: 'Something Went Wrong, try Again....'
                        });
                    });
            });
        }




        function loadParcelDataOnEditor() {
            hideunhideparcelSpanel();
            var plotID = document.getElementById("selectedParcelNo").innerHTML;
            console.log("Selected Parcel ID IS : ", plotID);




            var xhr = new XMLHttpRequest();
            var apiUrl = '../api/parcel/byParcelId/' + plotID;

            xhr.open('GET', apiUrl, true);
            xhr.setRequestHeader('accept', 'application/json');

            xhr.onload = function () {
                if (xhr.status === 200) {
                    var response = JSON.parse(xhr.responseText);
                    PopulateParcelDataOnEditor(response);



                } else {
                    console.error('Error fetching Tehsil data:', xhr.statusText);
                }
            };

            xhr.onerror = function () {
                console.error('Network error while fetching Tehsil data');
            };

            xhr.send();

        }
        function intimateDataTOOtherModule() {

            var plotID = document.getElementById("selectedParcelNo").innerHTML;
            console.log("i am ready to send data to module with parcel ID : ", plotID);




            var xhr = new XMLHttpRequest();
            var apiUrl = '../api/parcel/byParcelId/' + plotID;

            xhr.open('GET', apiUrl, true);
            xhr.setRequestHeader('accept', 'application/json');

            xhr.onload = function () {
                if (xhr.status === 200) {
                    var response = JSON.parse(xhr.responseText);
                    //   PopulateParcelDataOnEditor(response);
                    intimateWithData(response);



                } else {
                    console.error('Error fetching Tehsil data:', xhr.statusText);
                }
            };

            xhr.onerror = function () {
                console.error('Network error while fetching Tehsil data');
            };

            xhr.send();

        }

        function hideunhideadvSpanel() {

            var advSpanel = document.getElementById("advSpanel");
            advSpanel.classList.toggle("hidden");
            advSpanel.classList.toggle("visible");
        }

        function hideunhideparcelSpanel() {

            var parcelSpanel = document.getElementById("parcelSpanel");
            parcelSpanel.classList.remove("hidden");
            parcelSpanel.classList.add("visible");
        }

        function fetchDatabyParcelID() {
            var plotIdInput = document.getElementById("plotid");
            var inputValue = plotIdInput.value;

            var xhr = new XMLHttpRequest();
            var apiUrl = '../api/parcel/parcel/byParcelUniqeId/' + inputValue;

            xhr.open('GET', apiUrl, true);
            xhr.setRequestHeader('accept', 'application/json');

            xhr.onload = function () {
                if (xhr.status === 200) {
                    var response = JSON.parse(xhr.responseText);
                    loadsearchedparcel(response);

                } else {
                    console.error('Error fetching Tehsil data:', xhr.statusText);
                }
            };

            xhr.onerror = function () {
                console.error('Network error while fetching Tehsil data');
            };

            xhr.send();
        }


        function fetchDatabyCNIC() {
            var cnicIdInput = document.getElementById("cnicvalue");
            var inputValue = cnicIdInput.value;

            var xhr = new XMLHttpRequest();
            var apiUrl = '../api/GeoJSON/GetParcelbyCNIC/' + inputValue;

            xhr.open('GET', apiUrl, true);
            xhr.setRequestHeader('accept', 'application/json');

            xhr.onload = function () {
                if (xhr.status === 200) {
                    var response = JSON.parse(xhr.responseText);
                    loadsearchedparcel2(response);

                } else {
                    console.error('Error fetching parcel data:', xhr.statusText);
                }
            };

            xhr.onerror = function () {
                console.error('Network error while fetching Parcel data');
            };

            xhr.send();
        }

        function loadsearchedparcel(data) {
            data.forEach(parcel => {


                var container = document.getElementById('leftpanel');
                var container2 = document.getElementById('mappanel');

                document.getElementById("selectedParcelNo").innerHTML = parcel.parcel_id;

                container.style.display = 'block';


                container2.classList.add("col-md-9");
                container2.classList.remove("col-md-12");
                // console.log("Hello there is ma new", e.layer.feature.properties.plot_id);


                // Get the reference to the parcel container div
                var parcelContainer = document.getElementById("parcel-container");
                parcelContainer.innerHTML = "";
                // Get the reference to the parcel container div
                var personContainer = document.getElementById("persons-container");
                personContainer.innerHTML = "";


                console.log(parcel.parcel_id);
                var id = parcel.parcel_id;
                fetchAndPopulatePersons(id);
                fetchAndPopulateParcel(id);
                loaddata(id);

            });

        }
        function loadsearchedparcel2(data) {
            data.forEach(parcel => {

                var container = document.getElementById('leftpanel');
                var container2 = document.getElementById('mappanel');

                document.getElementById("selectedParcelNo").innerHTML = parcel.plot_id;

                container.style.display = 'block';


                container2.classList.add("col-md-9");
                container2.classList.remove("col-md-12");
                // console.log("Hello there is ma new", e.layer.feature.properties.plot_id);


                // Get the reference to the parcel container div
                var parcelContainer = document.getElementById("parcel-container");
                parcelContainer.innerHTML = "";
                // Get the reference to the parcel container div
                var personContainer = document.getElementById("persons-container");
                personContainer.innerHTML = "";



                console.log(parcel.plot_id);
                var id = parcel.plot_id;
                //   fetchAndPopulatePersons(id);
                //  fetchAndPopulateParcel(id);
                loaddata(id);

            });

        }


        var geojsonLayer;

        function loaddata(id) {

            fetch('../api/GeoJSON/' + id)
                .then(response => response.json())
                .then(data => {

                    // Iterate through each plot in the response
                    data.forEach(plot => {
                        // Convert WKT to GeoJSON
                        console.log("I am here  ---------------", plot.shape);
                        var wkt = wellknown.parse(plot.shape);
                        console.log(wkt);
                        if (geojsonLayer) {
                            map.removeLayer(geojsonLayer);
                        }
                        // Add GeoJSON to the map
                        geojsonLayer = L.geoJSON(wkt, {
                            onEachFeature: function (feature, layer) {
                                // Optionally, add a popup to each feature
                                var properties = feature.properties;
                                // Optionally, add a popup to each feature
                                //                    var popupContent = Object.keys(plot).map(function (key) {
                                //                        return key + ": " + plot[key];
                                //                    }).join("<br>");
                                var popupContent = Object.keys(plot).map(function (key) {
                                    return key + ": " + plot[key];

                                }).join("<br>");



                                // layer.bindPopup(popupContent);
                                layer.on('click', function (e) {
                                    // Update the existingPolygon coordinates
                                    console.log("now in load function ......")

                                    // Update the existingPolygon coordinates
                                    // map.removeLayer(geojsonLayer);
                                    fetchAndPopulatePersons(plot.plot_id);
                                    fetchAndPopulateParcel(plot.plot_id);
                                    existingPolygon.geometry.coordinates[0] = [];
                                    existingPolygon.geometry.coordinates[0] = e.target.feature.geometry.coordinates[0];

                                    //   var container = document.getElementById('leftpanel');
                                    //   var container2 = document.getElementById('mappanel');


                                    //   container.style.display = 'block';


                                    //     container2.classList.add("col-md-9");
                                    //     container2.classList.remove("col-md-12");
                                    console.log("Updated Ppolygons are are:");
                                    console.log(existingPolygon.geometry.coordinates[0]);

                                    // Create a new GeoJSON layer with the updated polygon
                                    drawnPolygons.clearLayers();

                                    var updatedPolygonLayer = L.geoJSON(existingPolygon).addTo(drawnPolygons);

                                    //   toggleSelection(updatedPolygonLayer);

                                    // Add the drawnPolygons layer group to the map
                                    //  drawnPolygons.addTo(map);
                                    console.log("updated are:");
                                    console.log(existingPolygon.geometry.coordinates);

                                    // Convert Leaflet polygon to Turf.js feature
                                    var turfPolygon = turf.polygon(e.target.feature.geometry.coordinates);
                                    // Calculate area using Turf.js
                                    var area = turf.area(turfPolygon);
                                    // area =area * 0.99725;
                                    console.log("Area in sqm updatednew: ", area);

                                    updatedPolygonLayer.setStyle({
                                        color: 'pink',  // Set your desired highlight color
                                        weight: 3,
                                        fillOpacity: 0.5
                                    });
                                    //area = area * 10.7639;



                                    //console.log("Area in feet: ", Math.round(area));
                                    //const inputFeet = Math.round(area);
                                    //const inputMauzaId = 1;
                                    //const inputFormat = 2;
                                    //const result = getAreaByFeet(inputFeet, inputMauzaId, inputFormat);
                                    //console.log(result);

                                    console.log("My new Area in KMF: ", sqmTOkmf2(area));



                                    //  document.getElementById("pdpanel").innerHTML += "Area fro selected parcel is: " + area + " (Square meters)";
                                    // Fit the map to the bounds of the updated polygon layer
                                    var bounds = updatedPolygonLayer.getBounds().pad(3);
                                    map.fitBounds(bounds);
                                });
                            }
                        }).addTo(map);
                        geojsonLayer.setStyle({
                            color: 'Red',  // Set your desired highlight color
                            weight: 4,
                            fillOpacity: 0
                        });
                        //  Fit the map to the bounds of the GeoJSON layer
                        map.fitBounds(geojsonLayer.getBounds().pad(3));

                    });
                })
                .catch(error => console.error('Error loading WKT geometries:', error));
        }




        //getting all the initial vector layer
        getJsonLayer();


        //// Function to remove all layers from the map
        //function removeAllLayers() {
        //    map.eachLayer(function (layer) {
        //        if (layer !== map) {
        //            map.removeLayer(layer);
        //        }
        //    });
        //}



        var geojsonLayer2;


        function loaddatabykhewatzone(idkhewat, idzone) {

            console.log("selected khewat is " + idkhewat + "Selected Zone is:" + idzone);
            fetch('../api/GeoJSON/GetParcelInfo/' + idzone + '/' + idkhewat)
                .then(response => response.json())
                .then(data => {

                    // Iterate through each plot in the response
                    data.forEach(plot => {
                        // Convert WKT to GeoJSON
                        console.log("I am here  ---------------", plot.shape);
                        var wkt = wellknown.parse(plot.shape);
                        console.log(wkt);
                        // Add GeoJSON to the map
                        geojsonLayer2 = L.geoJSON(wkt, {
                            style: { color: "yellow" },
                            onEachFeature: function (feature, layer) {
                                // Optionally, add a popup to each feature
                                var properties = feature.properties;
                                // Optionally, add a popup to each feature
                                //                    var popupContent = Object.keys(plot).map(function (key) {
                                //                        return key + ": " + plot[key];
                                //                    }).join("<br>");
                                var popupContent = Object.keys(plot).map(function (key) {
                                    return key + ": " + plot[key];

                                }).join("<br>");
                                // layer.bindPopup(popupContent);
                                layer.on('click', function (e) {

                                    var container = document.getElementById('leftpanel');
                                    var container2 = document.getElementById('mappanel');
                                    container.style.display = 'block';
                                    container2.classList.add("col-md-9");
                                    container2.classList.remove("col-md-12");
                                    document.getElementById("selectedParcelNo").innerHTML = plot.plot_id;
                                    fetchAndPopulatePersons(plot.plot_id);
                                    fetchAndPopulateParcel(plot.plot_id);
                                    existingPolygon.geometry.coordinates[0] = e.target.feature.geometry.coordinates[0];
                                    var updatedPolygonLayer = L.geoJSON(existingPolygon).addTo(drawnPolygons);
                                    drawnPolygons.addTo(map);
                                    console.log("updated are:");
                                    console.log(existingPolygon.geometry.coordinates);
                                    // Fit the map to the bounds of the updated polygon layer
                                    var bounds = updatedPolygonLayer.getBounds().pad(1);
                                    map.fitBounds(bounds);
                                });
                            }
                        }).addTo(map);


                        (geojsonLayer2).addTo(geojsonLayer3);




                    });//end foreach
                    //  Fit the map to the bounds of the GeoJSON layer
                    map.fitBounds(geojsonLayer3.getBounds().pad(1));
                })
                .catch(error => console.error('Error loading WKT geometries:', error));
        }
        const cutIdPrefix = 'cut_';
        var polygons = [];
        var existingPolygon = {
            "type": "Feature",
            "properties": {
                "id": "15245-1554",
                "color": "blue"
            },
            "geometry": {
                "type": "Polygon",
                "coordinates": [
                    [
                        [
                            74.310188,
                            31.47783
                        ],
                        [
                            74.311625,
                            31.478274
                        ],
                        [
                            74.311845,
                            31.477757
                        ],
                        [
                            74.310413,
                            31.477304
                        ],
                        [
                            74.310188,
                            31.47783
                        ]
                    ]
                ]
            }
        };
        var basePolygon = {
            "type": "Feature",
            "properties": {
                "id": "15245-1554",
                "color": "red"
            },
            "geometry": {
                "type": "MultiPolygon",
                "coordinates": [[]]
            }
        };
        L.geoJSON(basePolygon, { style: { color: "yellow" } }).addTo(map);
        var selectedLayer = null;


        function toggleSelection(layer) {
            // If the clicked layer is the currently selected layer, deselect it
            if (selectedLayer === layer) {
                resetLayerStyle(layer);
                // selectedLayer = null;
            } else {
                // Deselect the currently selected layer (if any)
                if (selectedLayer) {
                    resetLayerStyle(selectedLayer);
                }

                // Select the clicked layer
                selectedLayer = layer;
                highlightLayer(layer);
            }
        }


        map.on(L.Draw.Event.CREATED, function (event) {
            // alert("indise");
            document.getElementById("pdpanel").innerHTML += "<br>Editing Started....<br>";
            if (!isSplitButtonClicked) {
                return;
            }

            points.clearLayers();
            drawnLayer = event.layer;
            drawnGeoJSON = drawnLayer.toGeoJSON();
            drawnGeometry = drawnGeoJSON.geometry;

            // Instead of checking for LineString, consider any type of geometry drawn
            if (drawnGeometry) {
                drawnLines.addLayer(drawnLayer);
                drawnPolygons.clearLayers();
                drawnLines.clearLayers();

                if (existingPolygon) {

                    cutPolygon = polygonCut(existingPolygon.geometry, drawnGeometry, cutIdPrefix);
                    //  drawnPolygons.clearLayers(); // Clear existing polygons


                    if (cutPolygon != null) {



                        L.geoJSON(cutPolygon, {
                            style: cutPolygonStyle,
                            onEachFeature: function (feature, layer) {

                                // Convert Leaflet polygon to Turf.js feature
                                var turfPolygon = turf.polygon(feature.geometry.coordinates);
                                // Calculate area using Turf.js
                                var area = turf.area(turfPolygon);
                                area = parseFloat(area.toFixed(2));
                                console.log("Area is: ", area);
                                // Add a label to the polygon with its ID
                                layer.bindTooltip("Area: " + sqmTOkmf2(area), { permanent: true, direction: 'center', className: 'polygon-label' });




                                var coords = feature.geometry.coordinates[0]; // Assuming it's a simple polygon
                                for (var i = 0; i < coords.length - 1; i++) {
                                    var from = L.latLng(coords[i][1], coords[i][0]);
                                    var to = L.latLng(coords[i + 1][1], coords[i + 1][0]);
                                    var length1 = (from.distanceTo(to)) * 0.59651;
                                    var length = (length1).toFixed(0) + ' karam';


                                    // Calculate midpoints
                                    var mid1 = L.latLng((from.lat + to.lat) / 2, (from.lng + to.lng) / 2);
                                    var mid2 = L.latLng((mid1.lat + to.lat) / 2, (mid1.lng + to.lng) / 2);
                                    var mid3 = L.latLng((mid1.lat + from.lat) / 2, (mid1.lng + from.lng) / 2);

                                    // Calculate a point one-third of the way from start to end
                                    var oneThirdPoint = L.latLng((from.lat + mid1.lat) / 2, (from.lng + mid1.lng) / 2);

                                    // Calculate a point two-thirds of the way from start to end
                                    var twoThirdsPoint = L.latLng((mid1.lat + mid2.lat) / 2, (mid1.lng + mid2.lng) / 2);
                                    var circleIcon = L.divIcon({
                                        className: 'custom-circle-icon',
                                        iconSize: [5, 5], // Adjust the size of the icon
                                        html: '<div class="circle"></div>', // Use a div with a class for styling
                                    });
                                    // Add markers at midpoints
                                    // if (a) {a.remove();}
                                    // if (b) {b.remove();}
                                    // if (c) {c.remove();}
                                    // if (d) {d.remove();}
                                    var a = L.marker(mid1, { icon: circleIcon }); // Customize the marker icon as needed

                                    var b = L.marker(mid2, { icon: circleIcon }); // Customize the marker icon as needed

                                    var c = L.marker(mid3, { icon: circleIcon }); // Customize the marker icon as needed
                                    points.addLayer(a);
                                    points.addLayer(b);
                                    points.addLayer(c);


                                    // Add tooltips to each edge
                                    var d = L.polyline([from, to], { weight: 5, color: 'black' }) // Adjust styling as needed
                                        .bindTooltip(length, { permanent: true, className: 'custom-tooltip' });

                                    points.addLayer(d);
                                }

                                newPolygons.push(feature);

                            }
                        }).addTo(drawnPolygons).on('click', function (e) {
                            //    console.log(e.layer.feature.geometry.coordinates);
                            //    console.log(existingPolygon.geometry.coordinates);
                            e.layer.setStyle({
                                color: 'orange',  // Set your desired highlight color
                                weight: 4,
                                fillOpacity: 0.3
                            });

                            //    console.log("New Coordinates ----------");
                            //    console.log(basePolygon.geometry.coordinates);
                            existingPolygon.geometry.coordinates = e.layer.feature.geometry.coordinates;


                            var properties = e.layer.feature.properties;

                            var popupContent = 'Polygon ID: ' + properties.id + '<br>' +
                                'Color: ' + properties.color + '<br>' +
                                // Add more attributes as needed
                                'Additional Info: ' + (properties.additionalInfo || '') + '<br>';
                            // alert(popupContent);
                            // Geometry to match and remove
                            var geometryToRemove = e.layer.feature.geometry;

                            // Use Array.prototype.filter to remove the feature
                            var updatedPolygon = [];

                            updatedPolygon = newPolygons.filter(function (feature) {
                                // Custom condition to match based on geometry
                                return !areGeometriesEqual(feature.geometry, geometryToRemove);
                            });
                            newPolygons = updatedPolygon;
                            console.log('updated array is:');
                            // Log the updated array
                            console.log(newPolygons);

                            // Function to compare geometries
                            function areGeometriesEqual(geometry1, geometry2) {
                                return (
                                    JSON.stringify(geometry1) === JSON.stringify(geometry2)
                                );
                            }



                        });


                        // newPolygons.push(geometry);

                        //   turf.geomEach(cutPolygon, function (geometry) {

                        //     newPolygons.push(geometry);
                        //  //   basePolygon.geometry.coordinates.push(existingPolygon.geometry.coordinates);
                        //   });

                        // turf.geomEach(cutPolygon, function (geometry) {
                        //   // Check if the similar polygon already exists in newPolygons
                        //   const isPolygonExists = newPolygons.some((existingGeometry) => {
                        //     return JSON.stringify(existingGeometry.coordinates) === JSON.stringify(geometry.coordinates);
                        //   });

                        //   // If not, push the new polygon
                        //   if (!isPolygonExists) {
                        //     newPolygons.push(geometry);
                        //     basePolygon.geometry.coordinates.push(existingPolygon.geometry.coordinates);
                        //   }
                        // });



                        updateBasePolygon();

                        var bounds = drawnPolygons.getBounds().pad(1);
                        map.fitBounds(bounds);


                    } else {



                        L.geoJSON(existingPolygon, {
                            style: cutPolygonStyle
                        }).addTo(drawnPolygons);
                        //    newPolygons.push(existingPolygon.geometry);



                        //   updateBasePolygon(basePolygon.geometry.coordinates);
                    }



                }
            }
        });


        function highlightLayer(layer) {
            layer.setStyle({
                color: 'red',  // Set your desired highlight color
                weight: 5,
                fillOpacity: 0.3
            });
        }

        function resetLayerStyle(layer) {
            layer.setStyle({
                color: 'blue',  // Reset to the default color or your desired default style
                opacity: 0.5, fillOpacity: 0.1
            });
        }

        function updateBasePolygon() {
            // basePolygon.geometry.coordinates = coordinates;
            map.eachLayer(function (layer) {
                if (layer == basePolygons) {
                    layer.remove();

                }
            });
            basePolygons.clearLayers();
            newPolygons.forEach(function (geometry) {
                L.geoJSON(geometry, {
                    style: cutPolygonStyle,
                    onEachFeature: function (feature, layer) {
                        // Add a label to the polygon with its ID
                        //  layer.bindTooltip("ID: " + feature.properties.id, { permanent: true, direction: 'center', className: 'polygon-label-new' });
                    }
                }).addTo(basePolygons).on('click', function (e) {
                    console.log(e.layer.feature.geometry.coordinates);

                    // e.layer.setStyle({
                    //   color: 'blue',  // Set your desired highlight color
                    //   weight: 4,
                    //   fillOpacity: 0.3
                    // });
                    //   toggleSelection(e.layer);



                    existingPolygon.geometry.coordinates = e.layer.feature.geometry.coordinates;



                    // Geometry to match and remove
                    var geometryToRemove = e.layer.feature.geometry;

                    // Use Array.prototype.filter to remove the feature
                    var updatedPolygon = [];

                    updatedPolygon = newPolygons.filter(function (feature) {
                        // Custom condition to match based on geometry
                        return !areGeometriesEqual(feature.geometry, geometryToRemove);
                    });
                    newPolygons = updatedPolygon;
                    console.log('updated again array is:');
                    // Log the updated array
                    console.log(newPolygons);

                    // Function to compare geometries
                    function areGeometriesEqual(geometry1, geometry2) {
                        return (
                            JSON.stringify(geometry1) === JSON.stringify(geometry2)
                        );
                    }







                    var properties = e.layer.feature.properties;

                    var popupContent = 'Polygon ID: ' + properties.id + '<br>' +
                        'Color: ' + properties.color + '<br>' +
                        // Add more attributes as needed
                        'Additional Info: ' + (properties.additionalInfo || '') + '<br>';
                    alert(popupContent);


                });
                basePolygons.addTo(map);
                // basePolygons.bringToBack();

                // Update layer control

            });
            layerControl.addOverlay(basePolygons, 'Drawn Parcels');
            // Add this line to log the contents of newPolygons
            console.log("New Polygons:", newPolygons);
            //   updateNewPolygonsToTable(newPolygons);
        }


        if (existingPolygon) {
            L.geoJSON(existingPolygon, {
                style: cutPolygonStyle // Set the style for the existing polygonfi
            }).addTo(drawnPolygons);
            // Zoom to the bounds of the existing layer
            var bounds = drawnPolygons.getBounds().pad(1);
            //   map.fitBounds(bounds);
        }

        function cutPolygonStyle(feature) {
            var id, color;

            id = feature.properties.id;
            if (typeof (id) !== 'undefined') {
                id = id.substring(0, (cutIdPrefix.length + 1))
            }

            if (id == cutIdPrefix + '1')
                color = 'green';
            else if (id == cutIdPrefix + '2')
                color = 'red';
            else {
                color = '#3388ff';
            }
            return { color: color, opacity: 0.5, fillOpacity: 0.1 };
        }


        function updateNewPolygonsToTable(newPolygons) {

            console.log("I am here to update the geometry to temp table---------------");
            console.log(newPolygons);
            var counter = 1;
            newPolygons.forEach(parcel => {
                // Adjust this part based on your parcel data structure
                // console.log(parcel.properties.id);
                console.log(wellknown.stringify(parcel));
                // Convert Leaflet polygon to Turf.js feature
                var turfPolygon = turf.polygon(parcel.geometry.coordinates);
                // Calculate area using Turf.js
                var area = turf.area(turfPolygon);
                area = parseFloat(area.toFixed(2));

                area = area * 0.99725;

                area = area * 10.7639;
                area = Math.ceil(area);
                var pvalue = document.getElementById("selectedParcelNo").innerHTML;

                const parcelData = {

                    plot_id: counter,
                    Shape: wellknown.stringify(parcel),
                    area: area,
                    parent_plot_id: pvalue
                    // Add other properties if needed
                };
                console.log("Parcel Data that is being saved is " + JSON.stringify(parcelData));

                sendParceGeomDataToServer(parcelData);
                counter++;
            });

        }




        // Function to send data to the server
        function sendParceGeomDataToServer(parcelData) {
            // Make a POST request to the API endpoint
            fetch('../api/GeoJSON/InsertCutted', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(parcelData),
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! Status: ${response.status}`);
                    }

                    //// Check if the response is JSON
                    //const contentType = response.headers.get('content-type');
                    //if (contentType && contentType.indexOf('application/json') !== -1) {
                    //    return response.json();
                    //} else {
                    //    // Handle non-JSON response here
                    //    console.error('Non-JSON response:', response);
                    //    // You may want to throw an error or handle this case differently
                    //}
                })
                .then(data => {

                    console.log('Data sent successfully:', JSON.stringify(data));
                    alert(parcelData.parent_plot_id);
                    //  window.location.href = '/index2.html';
                    // Get the value from the text box
                    // var parcelSpanelplotidValue = document.getElementById('parcelSpanelplotid').innerHTML;
                    var parcelSpanelplotidValue = parcelData.parent_plot_id;

                    // Redirect to index2.html with the value as a query parameter
                    window.location.href = '/index2.html?parcelSpanelplotid=' + encodeURIComponent(parcelSpanelplotidValue);

                    // Handle success, if needed
                })
                .catch(error => {
                    console.error('Error sending data:', error);
                    // Handle error, if needed
                });
        }



        document.getElementById('SaveNewParcels').addEventListener('click', function () {

            updateNewPolygonsToTable(newPolygons);
            //window.location.href =  'index2.html';wind
            intimateDataTOOtherModule();
        });








        document.getElementById('splitButton').addEventListener('click', function () {

            // L.geoJSON(cutPolygon, {
            //   style: cutPolygonStyle,
            //   onEachFeature: function (feature, layer) {
            //     //  console.log(feature.geometry.coordinates);

            //     layer.bindTooltip("ID: " + feature.properties.id, { permanent: true, direction: 'center', className: 'polygon-label' });
            //     //   turf.geomEach(feature, function (geometry) {

            //     //   newPolygons.push(geometry);
            //   //  basePolygon.geometry.coordinates.push(feature.geometry.coordinates);
            //     //   updateBasePolygon(basePolygon.geometry.coordinates);
            //     //   console.log('-------');
            //     // });



            //   }
            // });
            var SaveNewParcels = document.getElementById("SaveNewParcels");
            SaveNewParcels.classList.remove("hidden");
            SaveNewParcels.classList.add("visible");

            updateBasePolygon();
            drawnPolygons.clearLayers();

            drawnLines.clearLayers();
            points.clearLayers();

            // window.location.href = '/new-page';

        });




        var isSplitButtonClicked = false;

        document.getElementById('initiateTransfer').addEventListener('click', function () {
            layersGroupremove();
            isSplitButtonClicked = true;
            var container = document.getElementById('leftpanel');
            var container2 = document.getElementById('mappanel');

            var buttonpanel = document.getElementById('buttonpanel');
            var filtersPanel = document.getElementById('filtersPanel');
            var advSpanel = document.getElementById('advSpanel');

            filtersPanel.style.display = 'none';
            container.style.display = 'none';
            advSpanel.style.display = 'none';

            container2.classList.remove("col-md-9");
            container2.classList.add("col-md-12");
            container2.style.height = '90%';



            buttonpanel.classList.remove("hidden");
            buttonpanel.classList.add("visible");
            //  map.removeLayer(selectedkhasraLayers);
            loadParcelDataOnEditor();


            //  container2.style.marginTop = '30vh';

            Swal.fire({
                icon: "warning",

                title: '<p class="urdu" style="color:green; font-size:1.2em">Taqseem Process Initiated ... </p> ',


                showConfirmButton: false,
                timer: 5000,

                allowOutsideClick: true,

                //customClass: {
                //    popup: 'custom-popup-class',
                //}
            });

        });



        var points = L.featureGroup().addTo(map);
        var drawnLayer, drawnGeoJSON, drawnGeometry;
        var newPolygons = [];

        newPolygons.forEach(function (geometry) {
            L.geoJSON(geometry, {
                style: cutPolygonStyle,
                onEachFeature: function (feature, layer) {
                    // Add a label to the polygon with its ID
                    //  layer.bindTooltip("ID: " + feature.properties.id, { permanent: true, direction: 'center', className: 'polygon-label' });
                }
            }).addTo(basePolygons);




        });


        var cutPolygon;

        document.getElementById('splitButton').addEventListener('click', function () {
            updateBasePolygon();
            drawnPolygons.clearLayers();
            drawnLines.clearLayers();
            points.clearLayers();

        });





        function polygonCut(polygon, line, idPrefix) {
            const THICK_LINE_UNITS = 'meters';
            const THICK_LINE_WIDTH = 0.001;
            var i, j, id, intersectPoints, lineCoords, forCut, forSelect;
            var thickLineString, thickLinePolygon, clipped, polyg, intersect;
            var polyCoords = [];
            var cutPolyGeoms = [];
            var cutFeatures = [];
            var offsetLine = [];
            var retVal = null;

            if (((polygon.type != 'Polygon') && (polygon.type != 'MultiPolygon')) || (line.type != 'LineString')) {
                return retVal;
            }

            if (typeof (idPrefix) === 'undefined') {
                idPrefix = '';
            }

            intersectPoints = turf.lineIntersect(polygon, line);
            if (intersectPoints.features.length == 0) {
                return retVal;
            }

            var lineCoords = turf.getCoords(line);
            if ((turf.booleanWithin(turf.point(lineCoords[0]), polygon) ||
                (turf.booleanWithin(turf.point(lineCoords[lineCoords.length - 1]), polygon)))) {
                return retVal;
            }

            offsetLine[0] = turf.lineOffset(line, THICK_LINE_WIDTH, { units: THICK_LINE_UNITS });
            offsetLine[1] = turf.lineOffset(line, -THICK_LINE_WIDTH, { units: THICK_LINE_UNITS });

            for (i = 0; i <= 1; i++) {
                forCut = i;
                forSelect = (i + 1) % 2;
                polyCoords = [];
                for (j = 0; j < line.coordinates.length; j++) {
                    polyCoords.push(line.coordinates[j]);
                }
                for (j = (offsetLine[forCut].geometry.coordinates.length - 1); j >= 0; j--) {
                    polyCoords.push(offsetLine[forCut].geometry.coordinates[j]);
                }
                polyCoords.push(line.coordinates[0]);

                thickLineString = turf.lineString(polyCoords);
                thickLinePolygon = turf.lineToPolygon(thickLineString);
                clipped = turf.difference(polygon, thickLinePolygon);

                cutPolyGeoms = [];
                for (j = 0; j < clipped.geometry.coordinates.length; j++) {
                    polyg = turf.polygon(clipped.geometry.coordinates[j]);
                    intersect = turf.lineIntersect(polyg, offsetLine[forSelect]);
                    if (intersect.features.length > 0) {
                        cutPolyGeoms.push(polyg.geometry.coordinates);
                    };
                };

                cutPolyGeoms.forEach(function (geometry, index) {
                    id = idPrefix + (i + 1) + '.' + (index + 1);
                    cutFeatures.push(turf.polygon(geometry, { id: id }));
                });
            }

            if (cutFeatures.length > 0) retVal = turf.featureCollection(cutFeatures);



            // Modify the style to hide the line and make polygons selectable
            var cuttedfeatures = turf.featureCollection(cutFeatures, {
                style: function (feature) {
                    return { fill: 'transparent', stroke: 'transparent' };
                },
                interactive: true
            });
            return cuttedfeatures;
        };




    </script>



</body>

</html>


