{{-- resources/views/peninjauan/partials/edit-tab-pengukuran.blade.php --}}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
<style>
.bg-gradient-primary {
    background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
}

.rtrw-legend-item {
    display: flex;
    align-items: center;
    padding: 8px 12px;
    margin: 5px;
    border-radius: 6px;
    background: white;
    border: 2px solid #e3e6f0;
    transition: all 0.3s ease;
}

.rtrw-legend-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    border-color: #4e73df;
}
 


.rtrw-legend-name {
    font-weight: 500;
    font-size: 13px;
    flex: 1;
}

.rtrw-legend-code {
    font-size: 11px;
    color: #6c757d;
    background: #f8f9fa;
    padding: 2px 8px;
    border-radius: 10px;
}
</style>
<!-- Pengukuran Tab -->
<div class="tab-pane fade" id="pengukuran" role="tabpanel">
    <div class="card">
        <div class="card-header">
            <h5 class="mb-0">Pengukuran, Persetujuan, Koordinat</h5>
        </div>
        <div class="card-body">
            <!-- BA Pengukuran Section -->
            <div class="row mb-4">
                <div class="col-12">
                    <h6 class="text-primary border-bottom pb-2 mb-3">BA Pengukuran Bidang Tanah</h6>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="nomor_ba_pengukuran" class="form-label">Nomor BA Pengukuran</label>
                        <input type="text" class="form-control" id="nomor_ba_pengukuran" name="nomor_ba_pengukuran"
                               value="{{ old('nomor_ba_pengukuran', $peninjauan->nomor_ba_pengukuran) }}" placeholder="Masukkan nomor BA">
                        @error('nomor_ba_pengukuran')
                            <div class="text-danger small mt-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="tanggal_pengukuran" class="form-label">Tanggal Pengukuran</label>
                        <input type="date" class="form-control" id="tanggal_pengukuran" name="tanggal_pengukuran"
                               value="{{ old('tanggal_pengukuran', $peninjauan->tanggal_pengukuran) }}">
                        @error('tanggal_pengukuran')
                            <div class="text-danger small mt-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
            </div>

            <!-- Keterangan Pengukuran -->
            <div class="row mb-4">
                <div class="col-12">
                    <h6 class="text-primary border-bottom pb-2 mb-3">Keterangan Pengukuran</h6>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="surat_tugas_nomor" class="form-label">Nomor Surat Tugas</label>
                        <input type="text" class="form-control" id="surat_tugas_nomor" name="surat_tugas_nomor"
                               value="{{ old('surat_tugas_nomor', $peninjauan->surat_tugas_nomor) }}" placeholder="Nomor surat tugas">
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="surat_tugas_tanggal" class="form-label">Tanggal Surat</label>
                        <input type="date" class="form-control" id="surat_tugas_tanggal" name="surat_tugas_tanggal"
                               value="{{ old('surat_tugas_tanggal', $peninjauan->surat_tugas_tanggal) }}">
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="petugas_ukur" class="form-label">Petugas Ukur</label>
                        <input type="text" class="form-control" id="petugas_ukur" name="petugas_ukur"
                               value="{{ old('petugas_ukur', $peninjauan->petugas_ukur) }}" placeholder="Nama petugas">
                    </div>
                </div>
            </div>
            <hr>
             <div class="row mb-4">
                <div class="col-12">
                    <h6 class="text-primary border-bottom pb-2 mb-3">BA Persetujuan Pengukuran Tanah</h6>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="no_ba_persetujuan_pengukuran_tanah" class="form-label">Nomor Surat Tugas</label>
                        <input type="text" class="form-control" id="no_ba_persetujuan_pengukuran_tanah" name="no_ba_persetujuan_pengukuran_tanah"
                               value="{{ old('no_ba_persetujuan_pengukuran_tanah', $peninjauan->no_ba_persetujuan_pengukuran_tanah) }}" placeholder="Nomor surat tugas">
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="tanggal_permohonan_pengukuran" class="form-label">Tanggal Permohonan</label>
                        <input type="date" class="form-control" id="tanggal_permohonan_pengukuran" name="tanggal_permohonan_pengukuran"
                               value="{{ old('tanggal_permohonan_pengukuran', $peninjauan->tanggal_permohonan_pengukuran) }}">
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="ukuran_patok" class="form-label">Ukuran Patok (cm)</label>
                        <input type="number" class="form-control" id="ukuran_patok" name="ukuran_patok"
                               value="{{ old('ukuran_patok', $peninjauan->ukuran_patok) }}" placeholder="Ukuran" step="0.01">
                    </div>
                </div>
            </div>
            <!-- Sistem Koordinat -->
            <div class="row mb-4">
                <div class="col-12">
                    <h6 class="text-primary border-bottom pb-2 mb-3">Sistem Koordinat</h6>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label class="form-label">Sistem Koordinat</label>
                        <input type="text" class="form-control bg-light" name="sistem_koordinat"
                               value="{{ old('sistem_koordinat', $peninjauan->sistem_koordinat ?? 'UTM') }}" readonly>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label for="cm_x" class="form-label">CM X</label>
                        <input type="text" class="form-control" id="cm_x" name="cm_x"
                               value="{{ old('cm_x', $peninjauan->cm_x) }}" placeholder="X">
                    </div>
                </div>
               
                <div class="col-md-3">
                    <div class="form-group">
                        <label for="tanggal_pengukuran_koordinat" class="form-label">Tanggal Pengukuran</label>
                        <input type="date" class="form-control" id="tanggal_pengukuran_koordinat"
                               name="tanggal_pengukuran_koordinat" value="{{ old('tanggal_pengukuran_koordinat', $peninjauan->tanggal_pengukuran_koordinat) }}">
                    </div>
                </div>
            </div>

            <!-- Map and Coordinates Section -->
            <div class="row">
                <div class="col-lg-12">
                    <div class="card border-primary">
                        <div class="card-header bg-primary text-white">
                            <h6 class="mb-0">Data Koordinat</h6>
                        </div>
                        <div class="card-body" style="max-height: 400px; overflow-y: auto;">
                            <table class="table table-sm table-hover">
                                <thead class="bg-light">
                                    <tr>
                                        <th width="15%">No</th>
                                        <th width="35%">Latitude</th>
                                        <th width="35%">Longitude</th>
                                        <th width="15%" class="text-center">Aksi</th>
                                    </tr>
                                </thead>
                                <tbody id="coordinatesList">
                                    <!-- Will be populated by JavaScript -->
                                </tbody>
                            </table>
                            <button type="button" onclick="addCoordinate()" class="btn btn-primary btn-sm btn-block">
                                + Tambah Koordinat
                            </button>
                        </div>
                    </div>

                    <!-- Area Information -->
                    <div class="card border-success mt-3">
                        <div class="card-header bg-success text-white">
                            <h6 class="mb-0">Informasi Area</h6>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-6">
                                    <div class="text-center">
                                        <div class="h4 text-success mb-1" id="calculatedArea">0 m²</div>
                                        <small class="text-muted">Luas Terukur</small>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="text-center">
                                        <div class="h4 text-info mb-1" id="coordinateCount">0</div>
                                        <small class="text-muted">Titik Koordinat</small>
                                    </div>
                                </div>
                            </div>
                            <div class="mt-2">
                                <div class="progress" style="height: 6px;">
                                    <div class="progress-bar bg-success" id="areaProgress" style="width: 0%"></div>
                                </div>
                                <small class="text-muted">Status: <span id="areaStatus">Menghitung...</span></small>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-lg-8">
                    <div class="card border-info">
                        <div class="card-header bg-info text-white d-flex justify-content-between align-items-center">
                            <h6 class="mb-0">Peta Lokasi</h6>
                            <div class="btn-group btn-group-sm">
                                <button type="button" onclick="centerMap()" class="btn btn-light btn-sm" title="Pusatkan peta">
                                    📍 Center
                                </button>
                                <button type="button" onclick="captureMap()" class="btn btn-warning btn-sm" title="Capture peta">
                                    📷 Capture
                                </button>
                            </div>
                        </div>
                        <div class="card-body p-0">
                            <div id="pengukuranMap" style="height: 450px; border-radius: 0 0 6px 6px;"></div>
                        </div>
                    </div>
                </div>
                <div class="col-lg-4 mt-3">
                <div class="card border-primary">
                    <div class="card-header bg-gradient-primary text-white d-flex justify-content-between align-items-center">
                        <h6 class="mb-0">
                            <i class="fas fa-layer-group"></i> Informasi Wilayah RTRW
                        </h6>
                        <div class="btn-group btn-group-sm">
                            <button type="button" onclick="loadRTRWData()" class="btn btn-light btn-sm" title="Refresh data RTRW">
                                <i class="fas fa-sync-alt"></i> Refresh
                            </button>
                            <button type="button" onclick="checkAllCoordinatesRTRW()" class="btn btn-warning btn-sm" title="Analisis semua koordinat">
                                <i class="fas fa-search-location"></i> Analisis
                            </button>
                            <button type="button" onclick="toggleRTRWOverlay()" class="btn btn-info btn-sm" title="Toggle tampilan RTRW di peta">
                                <i class="fas fa-eye"></i> Toggle
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="alert alert-info mb-3">
                                    <h6 class="alert-heading">
                                        <i class="fas fa-info-circle"></i> Fitur Pengecekan RTRW
                                    </h6>
                                    <hr>
                                    <ul class="small mb-0 pl-3">
                                        <li>Sistem akan otomatis mengecek setiap koordinat yang diinput</li>
                                        <li>Wilayah RTRW ditampilkan sebagai overlay di peta</li>
                                        <li>Klik tombol "Analisis" untuk melihat ringkasan lengkap</li>
                                        <li>Klik pada peta akan menampilkan informasi wilayah</li>
                                    </ul>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div id="rtrwSummary" class="border rounded p-3 bg-light">
                                    <div class="text-center text-muted py-3">
                                        <i class="fas fa-spinner fa-spin fa-2x mb-2"></i>
                                        <p class="mb-0 small">Memuat data RTRW...</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- RTRW Legend -->
                        <div class="mt-3">
                            <h6 class="font-weight-bold mb-3">
                                <i class="fas fa-palette"></i> Legend Wilayah RTRW:
                            </h6>
                            <div id="rtrwLegend" class="row">
                                <!-- Will be populated by JavaScript -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            </div>

            <!-- Hidden inputs for form submission -->
            <input type="hidden" name="luas_terukur_otomatis" id="luas_terukur_otomatis"
                   value="{{ old('luas_terukur_otomatis', $peninjauan->luas_terukur_otomatis) }}">
            <input type="hidden" name="map_image_data" id="map_image_data"
                   value="{{ old('map_image_data', $peninjauan->map_image_data) }}">
            <input type="hidden" name="polygon_bounds" id="polygon_bounds"
                   value="{{ old('polygon_bounds', $peninjauan->polygon_bounds) }}">
            <input type="hidden" name="coordinates_data" id="coordinates_input"
                   value="{{ old('coordinates_data', $peninjauan->coordinates_data) }}">
        </div>

        <!-- Form Actions -->
        <div class="card-footer bg-light">
            <div class="d-flex justify-content-between align-items-center">
               
                <div class="text-center">
                    <small class="text-muted">Status: <span id="saveStatus" class="text-info">Siap untuk disimpan</span></small>
                </div>
                
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
<script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@turf/turf@6.5.0/turf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    // Global variables for edit mode
    let pengukuranMap = null;
    let pengukuranPolygon = null;
    let pengukuranMarkers = [];
    let coordinateCount = 0;
    let coordinates = [];
    let calculatedArea = 0;
    let mapInitialized = false;

    // Load existing coordinates from database
    let existingCoordinates = [];

    @if(isset($peninjauan) && $peninjauan->coordinates && $peninjauan->coordinates->count() > 0)
        existingCoordinates = @json($peninjauan->coordinates->map(function($coord) {
            return ['lat' => $coord->latitude, 'lng' => $coord->longitude];
        }));
    @elseif(isset($peninjauan) && $peninjauan->coordinates_data)
        try {
            existingCoordinates = @json(json_decode($peninjauan->coordinates_data, true)) || [];
        } catch(e) {
            existingCoordinates = [];
        }
    @endif

    // Coordinate validation function
    function isValidCoordinate(lat, lng) {
        return (
            typeof lat === 'number' &&
            typeof lng === 'number' &&
            !isNaN(lat) &&
            !isNaN(lng) &&
            lat >= -90 &&
            lat <= 90 &&
            lng >= -180 &&
            lng <= 180
        );
    }

    // Show error message in map container
    function showMapError(message) {
        const mapContainer = document.getElementById('pengukuranMap');
        if (mapContainer) {
            mapContainer.innerHTML = `
                <div style="display: flex; align-items: center; justify-content: center; height: 450px; background: #f8f9fa; border: 2px dashed #dee2e6; flex-direction: column;">
                    <div style="color: #6c757d; font-size: 16px; margin-bottom: 10px;">⚠️ ${message}</div>
                    <button onclick="initPengukuranMap()" style="padding: 8px 16px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;">
                        Coba Lagi
                    </button>
                </div>
            `;
        }
    }

    // Load existing coordinates into table
    function loadExistingCoordinates() {
        const tbody = document.getElementById('coordinatesList');
        tbody.innerHTML = '';

        if (existingCoordinates && existingCoordinates.length > 0) {
            coordinates = existingCoordinates;
            coordinateCount = 0;

            coordinates.forEach((coord, index) => {
                coordinateCount++;
                const row = document.createElement('tr');
                row.id = `coord-${coordinateCount}`;
                row.innerHTML = `
                    <td class="align-middle font-weight-bold">${index + 1}</td>
                    <td>
                        <input type="text" class="form-control form-control-sm" id="lat_${coordinateCount}"
                               name="lat[${coordinateCount}]" value="${coord.lat}" onchange="updateMapAndCalculate()"
                               onblur="validateCoordinateInput(this)" placeholder="Latitude">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" id="lng_${coordinateCount}"
                               name="lng[${coordinateCount}]" value="${coord.lng}" onchange="updateMapAndCalculate()"
                               onblur="validateCoordinateInput(this)" placeholder="Longitude">
                    </td>
                    <td class="text-center">
                        <button type="button" onclick="removeCoordinate(${coordinateCount})"
                                class="btn btn-danger btn-sm" title="Hapus">×</button>
                    </td>
                `;
                tbody.appendChild(row);
            });
        } else {
            // Add default coordinates if none exist
            coordinates = [
                {lat: -1.2417, lng: 116.8730},
                {lat: -1.2418, lng: 116.8729},
                {lat: -1.2419, lng: 116.8731}
            ];

            coordinates.forEach((coord, index) => {
                coordinateCount++;
                const row = document.createElement('tr');
                row.id = `coord-${coordinateCount}`;
                row.innerHTML = `
                    <td class="align-middle font-weight-bold">${index + 1}</td>
                    <td>
                        <input type="text" class="form-control form-control-sm" id="lat_${coordinateCount}"
                               name="lat[${coordinateCount}]" value="${coord.lat}" onchange="updateMapAndCalculate()"
                               onblur="validateCoordinateInput(this)" placeholder="Latitude">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" id="lng_${coordinateCount}"
                               name="lng[${coordinateCount}]" value="${coord.lng}" onchange="updateMapAndCalculate()"
                               onblur="validateCoordinateInput(this)" placeholder="Longitude">
                    </td>
                    <td class="text-center">
                        <button type="button" onclick="removeCoordinate(${coordinateCount})"
                                class="btn btn-danger btn-sm" title="Hapus">×</button>
                    </td>
                `;
                tbody.appendChild(row);
            });
        }
    }

    // Enhanced map initialization with error handling
    function initPengukuranMap() {
        if (mapInitialized && pengukuranMap) {
            updateMapAndCalculate();
            return;
        }

        try {
            // Clear any existing map instance
            if (pengukuranMap) {
                pengukuranMap.remove();
                pengukuranMap = null;
            }

            // Check internet connection
            if (!navigator.onLine) {
                showMapError('Tidak ada koneksi internet');
                return;
            }

            // Initialize map with bounds checking
            const center = coordinates.length > 0 ? [coordinates[0].lat, coordinates[0].lng] : [-1.2417, 116.8730];
            const zoom = 18;

            // Validate coordinates before initialization
            if (isValidCoordinate(center[0], center[1])) {
                pengukuranMap = L.map('pengukuranMap', {
                    center: center,
                    zoom: zoom,
                    maxZoom: 20,
                    minZoom: 1,
                    zoomControl: true,
                    attributionControl: true,
                    preferCanvas: false
                });

                // Primary tile layer with error handling
                const osmLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                    attribution: '© OpenStreetMap contributors',
                    maxZoom: 20,
                    minZoom: 1,
                    errorTileUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
                    tileSize: 256,
                    subdomains: ['a', 'b', 'c'],
                    updateInterval: 200,
                    keepBuffer: 2
                });

                // Alternative tile layers as fallbacks
                const cartoDB = L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', {
                    attribution: '© CARTO © OpenStreetMap contributors',
                    maxZoom: 20,
                    minZoom: 1,
                    subdomains: 'abcd',
                    errorTileUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=='
                });

                // Handle tile errors and auto-fallback
                let tileErrorCount = 0;
                osmLayer.on('tileerror', function(error) {
                    tileErrorCount++;
                    console.warn('OSM tile error:', error, 'Count:', tileErrorCount);

                    if (tileErrorCount >= 3 && !pengukuranMap.hasLayer(cartoDB)) {
                        console.log('Switching to CartoDB due to tile errors');
                        pengukuranMap.removeLayer(osmLayer);
                        cartoDB.addTo(pengukuranMap);
                    }
                });

                // Add primary layer
                osmLayer.addTo(pengukuranMap);

                // Layer control
                const baseLayers = {
                    "OpenStreetMap": osmLayer,
                    "CartoDB Light": cartoDB
                };

                L.control.layers(baseLayers).addTo(pengukuranMap);

                // Add scale control
                L.control.scale({
                    position: 'bottomright',
                    metric: true,
                    imperial: false
                }).addTo(pengukuranMap);

                // Map event handlers
                pengukuranMap.on('click', function(e) {
                    const lat = e.latlng.lat;
                    const lng = e.latlng.lng;

                    if (isValidCoordinate(lat, lng)) {
                        const latRounded = lat.toFixed(8);
                        const lngRounded = lng.toFixed(8);

                        if (confirm(`Tambah koordinat baru?\nLatitude: ${latRounded}\nLongitude: ${lngRounded}`)) {
                            addCoordinateWithValues(latRounded, lngRounded);
                        }
                    } else {
                        alert('Koordinat tidak valid!');
                    }
                });

                // Handle map errors
                pengukuranMap.on('error', function(e) {
                    console.error('Map error:', e);
                    showMapError('Terjadi kesalahan pada peta. Silakan coba lagi.');
                });

                mapInitialized = true;

                // Load existing coordinates into table
                loadExistingCoordinates();

                // Initial update
                setTimeout(function() {
                    updateMapAndCalculate();
                }, 100);

            } else {
                throw new Error('Invalid initial coordinates');
            }

        } catch (error) {
            console.error('Error initializing map:', error);
            showMapError('Gagal memuat peta. Silakan coba lagi atau periksa koneksi internet.');
            mapInitialized = false;
        }
    }

    // All the other functions from the create version (copy from above)
    // Update area status function
    function updateAreaStatus(success, customMessage = null) {
        const areaStatus = document.getElementById('areaStatus');
        const areaProgress = document.getElementById('areaProgress');
        const saveStatus = document.getElementById('saveStatus');

        if (success && calculatedArea > 0) {
            document.getElementById('calculatedArea').textContent =
                calculatedArea.toLocaleString('id-ID', {maximumFractionDigits: 2}) + ' m²';

            if (areaStatus) {
                areaStatus.textContent = customMessage || 'Area berhasil dihitung';
                areaStatus.className = 'text-success';
            }

            if (areaProgress) {
                areaProgress.style.width = '100%';
                areaProgress.className = 'progress-bar bg-success';
            }

            if (saveStatus) {
                saveStatus.textContent = 'Siap untuk disimpan';
                saveStatus.className = 'text-success';
            }
        } else {
            document.getElementById('calculatedArea').textContent = '0 m²';

            if (areaStatus) {
                areaStatus.textContent = customMessage || 'Minimal 3 titik diperlukan';
                areaStatus.className = 'text-warning';
            }

            if (areaProgress) {
                const progress = Math.min((coordinates.length / 3) * 100, 100);
                areaProgress.style.width = progress + '%';
                areaProgress.className = 'progress-bar bg-warning';
            }

            if (saveStatus) {
                saveStatus.textContent = 'Belum siap';
                saveStatus.className = 'text-warning';
            }
        }
    }

    // Enhanced coordinate validation and map update
    function updateMapAndCalculate() {
        if (!pengukuranMap || !mapInitialized) {
            console.warn('Map not initialized, skipping update');
            return;
        }

        try {
            // Clear existing markers and polygon
            pengukuranMarkers.forEach(marker => {
                try {
                    if (pengukuranMap.hasLayer(marker)) {
                        pengukuranMap.removeLayer(marker);
                    }
                } catch (e) {
                    console.warn('Error removing marker:', e);
                }
            });
            pengukuranMarkers = [];

            if (pengukuranPolygon && pengukuranMap.hasLayer(pengukuranPolygon)) {
                try {
                    pengukuranMap.removeLayer(pengukuranPolygon);
                } catch (e) {
                    console.warn('Error removing polygon:', e);
                }
            }

            // Get coordinates from inputs with validation
            coordinates = [];
            const rows = document.querySelectorAll('#coordinatesList tr');

            rows.forEach((row, index) => {
                const coordId = row.id ? row.id.split('-')[1] : (index + 1);
                const latInput = document.getElementById(`lat_${coordId}`);
                const lngInput = document.getElementById(`lng_${coordId}`);

                if (latInput && lngInput && latInput.value && lngInput.value) {
                    const lat = parseFloat(latInput.value);
                    const lng = parseFloat(lngInput.value);

                    // Reset border colors
                    latInput.style.borderColor = '';
                    lngInput.style.borderColor = '';

                    // Validate coordinates
                    if (isValidCoordinate(lat, lng)) {
                        coordinates.push({lat: lat, lng: lng});

                        // Add numbered marker
                        try {
                            const marker = L.marker([lat, lng], {
                                icon: L.divIcon({
                                    className: 'custom-div-icon',
                                    html: `<div style="background: #28a745; color: white; width: 28px; height: 28px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 12px; font-weight: bold; border: 2px solid white; box-shadow: 0 2px 6px rgba(0,0,0,0.3);">${index + 1}</div>`,
                                    iconSize: [28, 28],
                                    iconAnchor: [14, 14]
                                })
                            });

                            marker.addTo(pengukuranMap);
                            pengukuranMarkers.push(marker);

                            // Add popup
                            marker.bindPopup(`
                                <strong>Titik ${index + 1}</strong><br>
                                Lat: ${lat.toFixed(8)}<br>
                                Lng: ${lng.toFixed(8)}
                            `);

                        } catch (markerError) {
                            console.error('Error adding marker:', markerError);
                        }
                    } else {
                        console.warn(`Invalid coordinate at index ${index}:`, lat, lng);
                        latInput.style.borderColor = '#dc3545';
                        lngInput.style.borderColor = '#dc3545';
                    }
                }
            });

            // Update coordinate count
            const countElement = document.getElementById('coordinateCount');
            if (countElement) {
                countElement.textContent = coordinates.length;
            }

            // Draw polygon if we have at least 3 valid coordinates
            if (coordinates.length >= 3) {
                try {
                    const latlngs = coordinates.map(coord => [coord.lat, coord.lng]);
                    pengukuranPolygon = L.polygon(latlngs, {
                        color: '#28a745',
                        fillColor: '#28a745',
                        fillOpacity: 0.3,
                        weight: 3,
                        dashArray: '5, 5'
                    });

                    pengukuranPolygon.addTo(pengukuranMap);

                    // Calculate area
                    calculatedArea = calculatePolygonArea();

                    // Add polygon popup
                    pengukuranPolygon.bindPopup(`
                        <strong>Area Polygon</strong><br>
                        Luas: ${calculatedArea.toLocaleString('id-ID', {maximumFractionDigits: 2})} m²<br>
                        Titik: ${coordinates.length}
                    `);

                    // Update UI
                    updateAreaStatus(true);

                    // Update hidden inputs
                    updateHiddenInputs();

                    // Fit map to polygon bounds
                    const bounds = pengukuranPolygon.getBounds();
                    if (bounds.isValid()) {
                        pengukuranMap.fitBounds(bounds, {padding: [10, 10]});
                    }

                } catch (polygonError) {
                    console.error('Error creating polygon:', polygonError);
                    updateAreaStatus(false, 'Error membuat polygon');
                }
            } else {
                updateAreaStatus(false, 'Minimal 3 titik diperlukan');
                updateHiddenInputs();
            }

        } catch (error) {
            console.error('Error updating map:', error);
            updateAreaStatus(false, 'Error updating map');
        }
    }

    // Update hidden inputs with current data
    function updateHiddenInputs() {
        try {
            // Update coordinates data
            const coordinatesInput = document.getElementById('coordinates_input');
            if (coordinatesInput) {
                coordinatesInput.value = JSON.stringify(coordinates);
            }

            // Update calculated area
            const areaInput = document.getElementById('luas_terukur_otomatis');
            if (areaInput) {
                areaInput.value = calculatedArea;
            }

            // Update polygon bounds
            if (pengukuranPolygon) {
                const bounds = pengukuranPolygon.getBounds();
                const boundsInput = document.getElementById('polygon_bounds');
                if (boundsInput && bounds.isValid()) {
                    boundsInput.value = JSON.stringify({
                        north: bounds.getNorth(),
                        south: bounds.getSouth(),
                        east: bounds.getEast(),
                        west: bounds.getWest()
                    });
                }
            }
        } catch (error) {
            console.error('Error updating hidden inputs:', error);
        }
    }

    // Add new coordinate row with optional values
    function addCoordinateWithValues(lat = '', lng = '') {
        coordinateCount++;
        const tbody = document.getElementById('coordinatesList');
        if (!tbody) return;

        const rowNumber = tbody.children.length + 1;

        const newRow = document.createElement('tr');
        newRow.id = `coord-${coordinateCount}`;
        newRow.innerHTML = `
            <td class="align-middle font-weight-bold">${rowNumber}</td>
            <td>
                <input type="text" class="form-control form-control-sm" id="lat_${coordinateCount}"
                       name="lat[${coordinateCount}]" value="${lat}" placeholder="Latitude"
                       onchange="updateMapAndCalculate()" onblur="validateCoordinateInput(this)">
            </td>
            <td>
                <input type="text" class="form-control form-control-sm" id="lng_${coordinateCount}"
                       name="lng[${coordinateCount}]" value="${lng}" placeholder="Longitude"
                       onchange="updateMapAndCalculate()" onblur="validateCoordinateInput(this)">
            </td>
            <td class="text-center">
                <button type="button" onclick="removeCoordinate(${coordinateCount})"
                        class="btn btn-danger btn-sm" title="Hapus">×</button>
            </td>
        `;
        tbody.appendChild(newRow);

        // Update map if values provided
        if (lat && lng) {
            setTimeout(updateMapAndCalculate, 100);
        }

        // Focus on the first input if no values provided
        if (!lat && !lng) {
            const newLatInput = document.getElementById(`lat_${coordinateCount}`);
            if (newLatInput) {
                newLatInput.focus();
            }
        }
    }

    // Add coordinate (wrapper for addCoordinateWithValues)
    function addCoordinate() {
        addCoordinateWithValues();
    }

    // Validate coordinate input on blur
    function validateCoordinateInput(input) {
        if (!input.value) return;

        const value = parseFloat(input.value);
        const isLat = input.name.includes('lat');

        if (!isNaN(value)) {
            if (isLat && (value < -90 || value > 90)) {
                input.style.borderColor = '#dc3545';
                input.title = 'Latitude harus antara -90 dan 90';
            } else if (!isLat && (value < -180 || value > 180)) {
                input.style.borderColor = '#dc3545';
                input.title = 'Longitude harus antara -180 dan 180';
            } else {
                input.style.borderColor = '';
                input.title = '';
            }
        } else {
            input.style.borderColor = '#dc3545';
            input.title = 'Harus berupa angka';
        }
    }

    // Remove coordinate row
    function removeCoordinate(id) {
        const row = document.getElementById(`coord-${id}`);
        if (!row) return;

        // Don't allow removal if only 3 coordinates left
        const totalRows = document.querySelectorAll('#coordinatesList tr').length;
        // if (totalRows <= 3) {
        //     alert('Minimal 3 koordinat harus tetap ada');
        //     return;
        // }

        if (confirm('Hapus koordinat ini?')) {
            row.remove();

            // Re-number rows
            const rows = document.querySelectorAll('#coordinatesList tr');
            rows.forEach((row, index) => {
                const firstTd = row.querySelector('td:first-child');
                if (firstTd) {
                    firstTd.textContent = index + 1;
                }
            });

            setTimeout(updateMapAndCalculate, 100);
        }
    }

    // Enhanced center map function
    function centerMap() {
        if (!pengukuranMap || !mapInitialized) {
            console.warn('Map not available for centering');
            return;
        }

        try {
            if (pengukuranPolygon) {
                const bounds = pengukuranPolygon.getBounds();
                if (bounds.isValid()) {
                    pengukuranMap.fitBounds(bounds, {padding: [20, 20]});
                    return;
                }
            }

            if (pengukuranMarkers.length > 0) {
                const group = new L.featureGroup(pengukuranMarkers);
                pengukuranMap.fitBounds(group.getBounds(), {padding: [20, 20]});
                return;
            }

            // Reset to default center
            const defaultCenter = coordinates.length > 0 ? [coordinates[0].lat, coordinates[0].lng] : [-1.2417, 116.8730];
            pengukuranMap.setView(defaultCenter, 18);

        } catch (error) {
            console.error('Error centering map:', error);
            try {
                pengukuranMap.setView([-1.2417, 116.8730], 18);
            } catch (fallbackError) {
                console.error('Error with fallback center:', fallbackError);
            }
        }
    }

    // Calculate polygon area using Shoelace formula
    function calculatePolygonArea() {
        if (coordinates.length < 3) return 0;

        try {
            let area = 0;
            const n = coordinates.length;

            for (let i = 0; i < n; i++) {
                const j = (i + 1) % n;
                area += coordinates[i].lat * coordinates[j].lng;
                area -= coordinates[j].lat * coordinates[i].lng;
            }

            area = Math.abs(area / 2);

            // Convert to square meters (approximation for Indonesia region)
            const latCenter = coordinates.reduce((sum, c) => sum + c.lat, 0) / n;
            const metersPerDegreeLng = 111319.9 * Math.cos(latCenter * Math.PI / 180);
            const metersPerDegreeLat = 111319.9;

            const areaInSquareMeters = area * metersPerDegreeLat * metersPerDegreeLng;

            return Math.round(areaInSquareMeters * 100) / 100;
        } catch (error) {
            console.error('Error calculating area:', error);
            return 0;
        }
    }

    // Enhanced map capture function with polygon support (same as create version)
    function captureMap() {
        if (!pengukuranMap || !mapInitialized || coordinates.length < 3) {
            Swal.fire({
                icon: 'warning',
                title: 'Capture Gagal',
                text: 'Harap tambahkan minimal 3 koordinat sebelum capture peta',
                confirmButtonColor: '#dc3545',
                confirmButtonText: '<i class="fas fa-times"></i> Tutup',
                width: '400px'
            });
            return;
        }

        const saveStatus = document.getElementById('saveStatus');
        if (saveStatus) {
            saveStatus.textContent = 'Sedang capture peta...';
            saveStatus.className = 'text-info';
        }

        // Use manual canvas drawing as primary method for reliability
        createManualMapImage();
    }
    // function autoCaptureMap() {
    //     if (!pengukuranMap || !mapInitialized || coordinates.length < 3) {
    //         Swal.fire({
    //             icon: 'warning',
    //             title: 'Capture Gagal',
    //             text: 'Harap tambahkan minimal 3 koordinat sebelum capture peta',
    //             confirmButtonColor: '#dc3545',
    //             confirmButtonText: '<i class="fas fa-times"></i> Tutup',
    //             width: '400px'
    //         });
    //         return;
    //     }

    //     const saveStatus = document.getElementById('saveStatus');
    //     if (saveStatus) {
    //         saveStatus.textContent = 'Sedang capture peta...';
    //         saveStatus.className = 'text-info';
    //     }

    //     // Use manual canvas drawing as primary method for reliability
    //     createManualMapImage();
    // }
    // Create manual map image by drawing on canvas (same as create version)
    function createManualMapImage() {
        const saveStatus = document.getElementById('saveStatus');

        try {
            const canvas = document.createElement('canvas');
            canvas.width = 800;
            canvas.height = 600;
            const ctx = canvas.getContext('2d');

            // Set background with subtle gradient
            const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
            gradient.addColorStop(0, '#f8f9fa');
            gradient.addColorStop(1, '#e9ecef');
            ctx.fillStyle = gradient;
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            if (coordinates.length >= 3) {
                // Calculate bounds
                const lats = coordinates.map(c => c.lat);
                const lngs = coordinates.map(c => c.lng);
                const minLat = Math.min(...lats);
                const maxLat = Math.max(...lats);
                const minLng = Math.min(...lngs);
                const maxLng = Math.max(...lngs);

                // Add padding
                const latPadding = (maxLat - minLat) * 0.15 || 0.002;
                const lngPadding = (maxLng - minLng) * 0.15 || 0.002;

                // Map coordinates to canvas
                function mapToCanvas(lat, lng) {
                    const x = ((lng - minLng + lngPadding) / (maxLng - minLng + 2 * lngPadding)) * (canvas.width - 60) + 30;
                    const y = ((maxLat - lat + latPadding) / (maxLat - minLat + 2 * latPadding)) * (canvas.height - 100) + 50;
                    return { x, y };
                }

                // Draw subtle grid lines
                ctx.strokeStyle = '#dee2e6';
                ctx.lineWidth = 0.5;
                ctx.setLineDash([2, 2]);

                for (let i = 1; i < 8; i++) {
                    const x = 30 + ((canvas.width - 60) / 8) * i;
                    const y = 50 + ((canvas.height - 100) / 8) * i;

                    ctx.beginPath();
                    ctx.moveTo(x, 50);
                    ctx.lineTo(x, canvas.height - 50);
                    ctx.stroke();

                    ctx.beginPath();
                    ctx.moveTo(30, y);
                    ctx.lineTo(canvas.width - 30, y);
                    ctx.stroke();
                }

                // Draw coordinate lines to each point
                ctx.strokeStyle = '#6c757d';
                ctx.lineWidth = 1;
                ctx.setLineDash([3, 3]);

                coordinates.forEach((coord, index) => {
                    const point = mapToCanvas(coord.lat, coord.lng);

                    // Vertical line
                    ctx.beginPath();
                    ctx.moveTo(point.x, 50);
                    ctx.lineTo(point.x, canvas.height - 50);
                    ctx.stroke();

                    // Horizontal line
                    ctx.beginPath();
                    ctx.moveTo(30, point.y);
                    ctx.lineTo(canvas.width - 30, point.y);
                    ctx.stroke();
                });

                // Draw polygon fill
                if (coordinates.length >= 3) {
                    ctx.fillStyle = 'rgba(40, 167, 69, 0.25)';
                    ctx.strokeStyle = '#28a745';
                    ctx.lineWidth = 3;
                    ctx.setLineDash([8, 4]);

                    ctx.beginPath();
                    coordinates.forEach((coord, index) => {
                        const point = mapToCanvas(coord.lat, coord.lng);
                        if (index === 0) {
                            ctx.moveTo(point.x, point.y);
                        } else {
                            ctx.lineTo(point.x, point.y);
                        }
                    });
                    ctx.closePath();
                    ctx.fill();
                    ctx.stroke();

                    // Draw polygon outline (solid)
                    ctx.strokeStyle = '#28a745';
                    ctx.lineWidth = 2;
                    ctx.setLineDash([]);
                    ctx.stroke();
                }

                // Draw connecting lines between points
                ctx.strokeStyle = '#17a2b8';
                ctx.lineWidth = 2;
                ctx.setLineDash([]);

                coordinates.forEach((coord, index) => {
                    if (index < coordinates.length - 1) {
                        const point1 = mapToCanvas(coord.lat, coord.lng);
                        const point2 = mapToCanvas(coordinates[index + 1].lat, coordinates[index + 1].lng);

                        ctx.beginPath();
                        ctx.moveTo(point1.x, point1.y);
                        ctx.lineTo(point2.x, point2.y);
                        ctx.stroke();
                    }
                });

                // Draw closing line
                if (coordinates.length > 2) {
                    const firstPoint = mapToCanvas(coordinates[0].lat, coordinates[0].lng);
                    const lastPoint = mapToCanvas(coordinates[coordinates.length - 1].lat, coordinates[coordinates.length - 1].lng);

                    ctx.beginPath();
                    ctx.moveTo(lastPoint.x, lastPoint.y);
                    ctx.lineTo(firstPoint.x, firstPoint.y);
                    ctx.stroke();
                }

                // Draw markers with shadows
                coordinates.forEach((coord, index) => {
                    const point = mapToCanvas(coord.lat, coord.lng);

                    // Draw shadow
                    ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
                    ctx.beginPath();
                    ctx.arc(point.x + 2, point.y + 2, 16, 0, 2 * Math.PI);
                    ctx.fill();

                    // Draw marker circle
                    ctx.fillStyle = '#28a745';
                    ctx.strokeStyle = '#ffffff';
                    ctx.lineWidth = 3;
                    ctx.setLineDash([]);

                    ctx.beginPath();
                    ctx.arc(point.x, point.y, 16, 0, 2 * Math.PI);
                    ctx.fill();
                    ctx.stroke();

                    // Draw number
                    ctx.fillStyle = '#ffffff';
                    ctx.font = 'bold 14px Arial';
                    ctx.textAlign = 'center';
                    ctx.textBaseline = 'middle';
                    ctx.fillText((index + 1).toString(), point.x, point.y);

                    // Add coordinate label
                    ctx.fillStyle = '#495057';
                    ctx.font = '9px Arial';
                    ctx.textAlign = 'center';
                    ctx.fillText(
                        `${coord.lat.toFixed(6)}, ${coord.lng.toFixed(6)}`,
                        point.x,
                        point.y + 30
                    );
                });

                // Add border
                ctx.strokeStyle = '#495057';
                ctx.lineWidth = 2;
                ctx.setLineDash([]);
                ctx.strokeRect(2, 2, canvas.width - 4, canvas.height - 4);
            }

            // Add header with title
            ctx.fillStyle = '#ffffff';
            ctx.fillRect(0, 0, canvas.width, 45);
            ctx.strokeStyle = '#dee2e6';
            ctx.lineWidth = 1;
            ctx.strokeRect(0, 0, canvas.width, 45);

            ctx.fillStyle = '#212529';
            ctx.font = 'bold 18px Arial';
            ctx.textAlign = 'center';
            ctx.fillText('PETA KOORDINAT PENGUKURAN BIDANG TANAH', canvas.width / 2, 28);

            // Add footer with information
            ctx.fillStyle = '#ffffff';
            ctx.fillRect(0, canvas.height - 50, canvas.width, 50);
            ctx.strokeRect(0, canvas.height - 50, canvas.width, 50);

            // Left side info
            ctx.fillStyle = '#495057';
            ctx.font = 'bold 12px Arial';
            ctx.textAlign = 'left';
            ctx.fillText(`Luas Area: ${calculatedArea.toLocaleString('id-ID')} m²`, 20, canvas.height - 30);
            ctx.fillText(`Jumlah Titik: ${coordinates.length}`, 20, canvas.height - 15);

            // Center info
            ctx.textAlign = 'center';
            ctx.fillText('Sistem Koordinat: UTM', canvas.width / 2, canvas.height - 30);
            ctx.fillText(`Skala: 1:${Math.round(1000 + coordinates.length * 100)}`, canvas.width / 2, canvas.height - 15);

            // Right side info
            ctx.textAlign = 'right';
            ctx.fillText(`Tanggal: ${new Date().toLocaleDateString('id-ID')}`, canvas.width - 20, canvas.height - 30);
            ctx.fillText(`Waktu: ${new Date().toLocaleTimeString('id-ID')}`, canvas.width - 20, canvas.height - 15);

            // Save the image
            const imageData = canvas.toDataURL('image/png');
            document.getElementById('map_image_data').value = imageData;

            if (saveStatus) {
                saveStatus.textContent = 'Peta berhasil di-capture! (Edit Mode)';
                saveStatus.className = 'text-success';
            }

            console.log('Map captured successfully in edit mode, image size:', imageData.length, 'bytes');

        } catch (error) {
            console.error('Error creating manual map image:', error);

            if (saveStatus) {
                saveStatus.textContent = 'Error capture peta';
                saveStatus.className = 'text-danger';
            }

            // Simplified fallback
            fallbackCapture();
        }
    }

    // Fallback capture method
    function fallbackCapture() {
        try {
            const mapData = {
                coordinates: coordinates,
                bounds: pengukuranPolygon ? pengukuranPolygon.getBounds() : null,
                center: pengukuranMap ? pengukuranMap.getCenter() : null,
                zoom: pengukuranMap ? pengukuranMap.getZoom() : 18,
                calculatedArea: calculatedArea,
                timestamp: new Date().toISOString(),
                mode: 'edit'
            };

            document.getElementById('map_image_data').value = JSON.stringify(mapData);

            const saveStatus = document.getElementById('saveStatus');
            if (saveStatus) {
                saveStatus.textContent = 'Data peta berhasil disimpan (Edit)';
                saveStatus.className = 'text-success';
            }
        } catch (error) {
            console.error('Error in fallback capture:', error);
            const saveStatus = document.getElementById('saveStatus');
            if (saveStatus) {
                saveStatus.textContent = 'Error menyimpan data peta';
                saveStatus.className = 'text-danger';
            }
        }
    }

    // Auto-capture when coordinates change (debounced)
    let captureTimeout;
    function autoCapture() {
        if (coordinates.length >= 3 && calculatedArea > 0) {
            if (captureTimeout) {
                clearTimeout(captureTimeout);
            }

            captureTimeout = setTimeout(function() {
                captureMap();
            }, 2000);
        }
    }

    // Initialize when document ready and tab is shown
    $(document).ready(function() {
        // Initialize map when pengukuran tab is shown
        $('a[href="#pengukuran"]').on('shown.bs.tab', function() {
            setTimeout(function() {
                if (!mapInitialized) {
                    initPengukuranMap();
                } else {
                    updateMapAndCalculate();
                }
            }, 100);
        });

        // Handle online/offline status
        window.addEventListener('online', function() {
            console.log('Connection restored');
            if (pengukuranMap && mapInitialized) {
                pengukuranMap.eachLayer(function(layer) {
                    if (layer.options && layer.options.attribution) {
                        layer.redraw();
                    }
                });
            }
        });

        window.addEventListener('offline', function() {
            console.log('Connection lost');
        });

        // Auto-save coordinates when they change
        $(document).on('change', 'input[name^="lat"], input[name^="lng"]', function() {
            setTimeout(function() {
                updateMapAndCalculate();
                autoCapture();
            }, 500);
        });
    });

    // Navigation functions
    function nextTab() {
        const activeTab = $('.nav-tabs .nav-link.active');
        const nextTab = activeTab.parent().next().find('.nav-link');
        if (nextTab.length > 0) {
            nextTab.tab('show');
            window.scrollTo({ top: 0, behavior: 'smooth' });
        } else {
            // If this is the last tab, you might want to submit the form
            console.log('This is the last tab');
        }
    }

    function previousTab() {
        const activeTab = $('.nav-tabs .nav-link.active');
        const prevTab = activeTab.parent().prev().find('.nav-link');
        if (prevTab.length > 0) {
            prevTab.tab('show');
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }
    }

    // Save draft function
    function saveDraft() {
        const formData = new FormData(document.querySelector('form'));
        formData.append('save_as_draft', '1');

        // Add coordinates if available
        if (coordinates.length > 0) {
            formData.set('coordinates_data', JSON.stringify(coordinates));
        }

        // Show loading
        const draftBtn = $('button:contains("Simpan Draft")');
        const originalText = draftBtn.html();
        draftBtn.html('<i class="fas fa-spinner fa-spin"></i> Menyimpan...').prop('disabled', true);

        $.ajax({
            url: window.location.href, // Use current URL for edit
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') || $('input[name="_token"]').val()
            },
            success: function(response) {
                if (typeof toastr !== 'undefined') {
                    toastr.success('Draft berhasil disimpan!');
                } else {
                    alert('Draft berhasil disimpan!');
                }

                // Mark form as unchanged
                if (typeof formChanged !== 'undefined') {
                    formChanged = false;
                }
            },
            error: function(xhr) {
                console.error('Save draft error:', xhr);
                let errorMsg = 'Gagal menyimpan draft';

                if (xhr.status === 422) {
                    const errors = xhr.responseJSON?.errors;
                    if (errors) {
                        errorMsg = 'Validation errors: ' + Object.values(errors).flat().join(', ');
                    }
                } else if (xhr.status === 419) {
                    errorMsg = 'Session expired. Silakan refresh halaman.';
                } else if (xhr.responseJSON?.message) {
                    errorMsg = xhr.responseJSON.message;
                }

                if (typeof toastr !== 'undefined') {
                    toastr.error(errorMsg);
                } else {
                    alert(errorMsg);
                }
            },
            complete: function() {
                draftBtn.html(originalText).prop('disabled', false);
            }
        });
    }

    // Export functions for external access
    window.initPengukuranMap = initPengukuranMap;
    window.updateMapAndCalculate = updateMapAndCalculate;
    window.addCoordinate = addCoordinate;
    window.removeCoordinate = removeCoordinate;
    window.centerMap = centerMap;
    window.captureMap = captureMap;
    window.validateCoordinateInput = validateCoordinateInput;
    window.nextTab = nextTab;
    window.previousTab = previousTab;
    window.saveDraft = saveDraft;

    console.log('Edit pengukuran tab loaded successfully');
</script>

<script>
// Global variables untuk RTRW data
let rtrwData = [];
let rtrwLayers = [];
let isCheckingRTRW = false;

// Load RTRW data dari database
async function loadRTRWData() {
    try {
        const response = await fetch('{{ route("rtrw.api.all") }}'); // Route baru untuk API
        if (!response.ok) throw new Error('Gagal memuat data RTRW');
        
        rtrwData = await response.json();
        console.log('RTRW data loaded:', rtrwData.length, 'areas');
        
        // Tampilkan RTRW overlay di map
        displayRTRWOverlay();
        
        return rtrwData;
    } catch (error) {
        console.error('Error loading RTRW data:', error);
        return [];
    }
}

// Tampilkan RTRW sebagai overlay di map
function displayRTRWOverlay() {
    if (!pengukuranMap || !mapInitialized || rtrwData.length === 0) return;
    
    // Hapus layer RTRW yang lama
    rtrwLayers.forEach(layer => {
        if (pengukuranMap.hasLayer(layer)) {
            pengukuranMap.removeLayer(layer);
        }
    });
    rtrwLayers = [];
    
    // Tambahkan layer RTRW baru
    rtrwData.forEach(rtrw => {
        try {
            const geojson = typeof rtrw.geojson === 'string' 
                ? JSON.parse(rtrw.geojson) 
                : rtrw.geojson;
            
            const layer = L.geoJSON(geojson, {
                style: {
                    color: rtrw.warna || '#3388ff',
                    weight: 2,
                    opacity: 0.6,
                    fillColor: rtrw.warna || '#3388ff',
                    fillOpacity: 0.1,
                    dashArray: '5, 10'
                },
                onEachFeature: function(feature, layer) {
                    layer.bindPopup(`
                        <div style="font-family: Arial, sans-serif;">
                            <strong style="color: ${rtrw.warna}; font-size: 14px;">
                                ${rtrw.nama_rtrw}
                            </strong>
                            <hr style="margin: 5px 0;">
                            <div style="font-size: 12px;">
                                <div style="margin: 3px 0;">
                                    <strong>Warna:</strong> 
                                    <span style="display: inline-block; width: 20px; height: 12px; background: ${rtrw.warna}; border: 1px solid #ccc; vertical-align: middle;"></span>
                                    ${rtrw.warna}
                                </div>
                            </div>
                        </div>
                    `);
                }
            });
            
            layer.addTo(pengukuranMap);
            rtrwLayers.push(layer);
            
        } catch (error) {
            console.error('Error displaying RTRW:', rtrw.nama_rtrw, error);
        }
    });
}

// Cek apakah titik berada dalam polygon RTRW menggunakan Turf.js
function checkPointInRTRW(lat, lng) {
    const point = turf.point([lng, lat]);
    const results = [];
    
    rtrwData.forEach(rtrw => {
        try {
            const geojson = typeof rtrw.geojson === 'string' 
                ? JSON.parse(rtrw.geojson) 
                : rtrw.geojson;
            
            // Handle FeatureCollection
            if (geojson.type === 'FeatureCollection') {
                geojson.features.forEach(feature => {
                    if (turf.booleanPointInPolygon(point, feature)) {
                        results.push(rtrw);
                    }
                });
            } 
            // Handle single Feature
            else if (geojson.type === 'Feature') {
                if (turf.booleanPointInPolygon(point, geojson)) {
                    results.push(rtrw);
                }
            }
            // Handle direct Geometry
            else if (geojson.type === 'Polygon' || geojson.type === 'MultiPolygon') {
                const feature = turf.feature(geojson);
                if (turf.booleanPointInPolygon(point, feature)) {
                    results.push(rtrw);
                }
            }
        } catch (error) {
            console.error('Error checking RTRW:', rtrw.nama_rtrw, error);
        }
    });
    
    return results;
}

// Tampilkan popup informasi RTRW
function showRTRWPopup(rtrwList, lat, lng) {
    if (rtrwList.length === 0) {
        Swal.fire({
            icon: 'info',
            title: 'Lokasi Koordinat',
            html: `
                <div style="text-align: left;">
                    <p><strong>Koordinat:</strong></p>
                    <p>Latitude: ${lat.toFixed(8)}</p>
                    <p>Longitude: ${lng.toFixed(8)}</p>
                    <hr>
                    <p style="color: #6c757d;">
                        <i class="fas fa-info-circle"></i> 
                        Titik ini <strong>tidak berada</strong> dalam area RTRW yang terdaftar
                    </p>
                </div>
            `,
            confirmButtonColor: '#007bff',
            confirmButtonText: 'OK'
        });
    } else {
        const areasHTML = rtrwList.map(rtrw => `
            <div style="border: 2px solid ${rtrw.warna}; padding: 10px; margin: 8px 0; border-radius: 6px; background: ${rtrw.warna}15;">
                <div style="display: flex; align-items: center; margin-bottom: 5px;">
                    <div style="width: 30px; height: 30px; background: ${rtrw.warna}; border-radius: 4px; margin-right: 10px; border: 2px solid white; box-shadow: 0 2px 4px rgba(0,0,0,0.2);"></div>
                    <strong style="font-size: 16px; color: ${rtrw.warna};">${rtrw.nama_rtrw}</strong>
                </div>
                <div style="font-size: 13px; color: #495057; margin-left: 40px;">
                    <div><i class="fas fa-palette"></i> Warna: ${rtrw.warna}</div>
                </div>
            </div>
        `).join('');
        
        Swal.fire({
            icon: 'success',
            title: `<i class="fas fa-map-marked-alt"></i> Wilayah Ditemukan!`,
            html: `
                <div style="text-align: left;">
                    <div style="background: #e7f3ff; padding: 10px; border-radius: 6px; margin-bottom: 15px;">
                        <p style="margin: 5px 0;"><strong>Koordinat:</strong></p>
                        <p style="margin: 5px 0; font-family: monospace;">Lat: ${lat.toFixed(8)}</p>
                        <p style="margin: 5px 0; font-family: monospace;">Lng: ${lng.toFixed(8)}</p>
                    </div>
                    <hr>
                    <p style="margin: 10px 0;"><strong>Titik ini berada di area:</strong></p>
                    ${areasHTML}
                    <div style="margin-top: 15px; padding: 10px; background: #fff3cd; border-radius: 6px; border-left: 4px solid #ffc107;">
                        <small style="color: #856404;">
                            <i class="fas fa-info-circle"></i> 
                            Ditemukan ${rtrwList.length} wilayah RTRW
                        </small>
                    </div>
                </div>
            `,
            width: '600px',
            confirmButtonColor: '#28a745',
            confirmButtonText: '<i class="fas fa-check"></i> Mengerti'
        });
    }
}

// Check all coordinates against RTRW
function checkAllCoordinatesRTRW() {
    if (coordinates.length === 0) {
        Swal.fire({
            icon: 'warning',
            title: 'Tidak Ada Koordinat',
            text: 'Silakan tambahkan koordinat terlebih dahulu',
            confirmButtonColor: '#ffc107'
        });
        return;
    }
    
    if (rtrwData.length === 0) {
        Swal.fire({
            icon: 'info',
            title: 'Data RTRW Kosong',
            text: 'Tidak ada data RTRW yang tersimpan di database',
            confirmButtonColor: '#17a2b8'
        });
        return;
    }
    
    isCheckingRTRW = true;
    
    // Analisis semua koordinat
    const analysis = {
        totalPoints: coordinates.length,
        pointsInArea: 0,
        pointsOutside: 0,
        areas: {}
    };
    
    coordinates.forEach((coord, index) => {
        const results = checkPointInRTRW(coord.lat, coord.lng);
        
        if (results.length > 0) {
            analysis.pointsInArea++;
            results.forEach(rtrw => {
                if (!analysis.areas[rtrw.nama_rtrw]) {
                    analysis.areas[rtrw.nama_rtrw] = {
                        info: rtrw,
                        points: []
                    };
                }
                analysis.areas[rtrw.nama_rtrw].points.push(index + 1);
            });
        } else {
            analysis.pointsOutside++;
        }
    });
    
    // Generate summary HTML
    const areasHTML = Object.entries(analysis.areas).map(([name, data]) => `
        <div style="border: 2px solid ${data.info.warna}; padding: 12px; margin: 10px 0; border-radius: 8px; background: ${data.info.warna}15;">
            <div style="display: flex; align-items: center; margin-bottom: 8px;">
                <div style="width: 35px; height: 35px; background: ${data.info.warna}; border-radius: 6px; margin-right: 12px; border: 2px solid white; box-shadow: 0 2px 6px rgba(0,0,0,0.2);"></div>
                <div>
                    <strong style="font-size: 16px; color: ${data.info.warna};">${name}</strong>
                    <div style="font-size: 12px; color: #6c757d;">${data.info.warna}</div>
                </div>
            </div>
            <div style="margin-left: 47px; font-size: 13px;">
                <div style="background: white; padding: 8px; border-radius: 4px; margin-top: 5px;">
                    <i class="fas fa-map-pin" style="color: ${data.info.warna};"></i> 
                    <strong>Titik yang masuk:</strong> ${data.points.join(', ')}
                    <span style="float: right; background: ${data.info.warna}; color: white; padding: 2px 8px; border-radius: 12px; font-size: 11px;">
                        ${data.points.length} titik
                    </span>
                </div>
            </div>
        </div>
    `).join('');
    
    const summaryHTML = `
        <div style="text-align: left;">
            <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-bottom: 20px;">
                <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 15px; border-radius: 8px; color: white; text-align: center;">
                    <div style="font-size: 28px; font-weight: bold;">${analysis.totalPoints}</div>
                    <div style="font-size: 12px; opacity: 0.9;">Total Titik</div>
                </div>
                <div style="background: linear-gradient(135deg, #28a745 0%, #20c997 100%); padding: 15px; border-radius: 8px; color: white; text-align: center;">
                    <div style="font-size: 28px; font-weight: bold;">${analysis.pointsInArea}</div>
                    <div style="font-size: 12px; opacity: 0.9;">Dalam Area</div>
                </div>
                <div style="background: linear-gradient(135deg, #ffc107 0%, #ff6b6b 100%); padding: 15px; border-radius: 8px; color: white; text-align: center;">
                    <div style="font-size: 28px; font-weight: bold;">${analysis.pointsOutside}</div>
                    <div style="font-size: 12px; opacity: 0.9;">Di Luar Area</div>
                </div>
            </div>
            
            ${Object.keys(analysis.areas).length > 0 ? `
                <hr style="margin: 15px 0;">
                <h6 style="color: #495057; margin-bottom: 15px;">
                    <i class="fas fa-layer-group"></i> Detail Wilayah RTRW:
                </h6>
                ${areasHTML}
            ` : `
                <div style="padding: 20px; background: #fff3cd; border-radius: 8px; text-align: center; border-left: 4px solid #ffc107;">
                    <i class="fas fa-exclamation-triangle" style="font-size: 24px; color: #856404; margin-bottom: 10px;"></i>
                    <p style="color: #856404; margin: 0;">Tidak ada titik yang berada dalam area RTRW yang terdaftar</p>
                </div>
            `}
            
            ${analysis.pointsOutside > 0 ? `
                <div style="margin-top: 15px; padding: 12px; background: #f8d7da; border-radius: 6px; border-left: 4px solid #dc3545;">
                    <small style="color: #721c24;">
                        <i class="fas fa-info-circle"></i> 
                        <strong>Perhatian:</strong> ${analysis.pointsOutside} titik berada di luar semua area RTRW
                    </small>
                </div>
            ` : ''}
        </div>
    `;
    
    Swal.fire({
        icon: analysis.pointsInArea > 0 ? 'success' : 'warning',
        title: '<i class="fas fa-chart-pie"></i> Analisis Wilayah RTRW',
        html: summaryHTML,
        width: '700px',
        confirmButtonColor: analysis.pointsInArea > 0 ? '#28a745' : '#ffc107',
        confirmButtonText: '<i class="fas fa-check-circle"></i> Mengerti',
        showCloseButton: true
    });
    
    isCheckingRTRW = false;
}

// Override fungsi addCoordinateWithValues untuk auto-check RTRW
const originalAddCoordinateWithValues = window.addCoordinateWithValues;
window.addCoordinateWithValues = function(lat = '', lng = '') {
    // Call original function
    originalAddCoordinateWithValues(lat, lng);
    
    // Auto check RTRW jika koordinat valid
    if (lat && lng && rtrwData.length > 0) {
        setTimeout(() => {
            const numLat = parseFloat(lat);
            const numLng = parseFloat(lng);
            
            if (isValidCoordinate(numLat, numLng)) {
                const results = checkPointInRTRW(numLat, numLng);
                
                if (results.length > 0) {
                    // Tampilkan notifikasi singkat
                    if (typeof toastr !== 'undefined') {
                        toastr.success(`Koordinat masuk di area: ${results.map(r => r.nama_rtrw).join(', ')}`, 'RTRW Ditemukan', {
                            timeOut: 3000,
                            closeButton: true
                        });
                    }
                }
            }
        }, 500);
    }
};

// Override map click handler untuk auto-check RTRW
const originalMapOnClick = function(e) {
    const lat = e.latlng.lat;
    const lng = e.latlng.lng;

    if (isValidCoordinate(lat, lng)) {
        const latRounded = lat.toFixed(8);
        const lngRounded = lng.toFixed(8);
        
        // Check RTRW terlebih dahulu
        const rtrwResults = checkPointInRTRW(parseFloat(latRounded), parseFloat(lngRounded));
        
        let message = rtrwResults.length > 0 
            ? `<div style="text-align: left;">
                 <hr>
                 <p><i class="fas fa-map-marker-alt"></i> Lokasi ini berada di area:</p>
                 ${rtrwResults.map(r => `<div style="margin-left: 20px;">• ${r.nama_rtrw}</div>`).join('')}
               </div>`
            : `<div style="text-align: left;">
                
                 <p style="color: #856404;">
                     <i class="fas fa-exclamation-triangle"></i> 
                     Lokasi ini tidak berada dalam area RTRW yang terdaftar
                 </p>
               </div>`;

        Swal.fire({
            icon: rtrwResults.length > 0 ? 'success' : 'warning',
            title: 'Informasi',
            html: message,
            showCancelButton: true,
            confirmButtonColor: '#28a745',
            cancelButtonColor: '#dc3545',
            confirmButtonText: '<i class="fas fa-check"></i> OK',
            cancelButtonText: '<i class="fas fa-times"></i> Tutup',
            width: '500px'
        }).then((result) => {
            if (result.isConfirmed) {
                // addCoordinateWithValues(latRounded, lngRounded);
                
                // Show detailed popup if in RTRW area
                if (rtrwResults.length > 0) {
                    setTimeout(() => {
                        showRTRWPopup(rtrwResults, parseFloat(latRounded), parseFloat(lngRounded));
                    }, 500);
                }
            }
        });
    } else {
        Swal.fire({
            icon: 'error',
            title: 'Koordinat Tidak Valid',
            text: 'Koordinat yang diklik tidak valid!',
            confirmButtonColor: '#dc3545',
            confirmButtonText: '<i class="fas fa-times"></i> Tutup',
            width: '400px'
        });
    }
};

// Initialize RTRW checking saat map sudah ready
const originalInitPengukuranMap = window.initPengukuranMap;
window.initPengukuranMap = async function() {
    // Call original init
    await originalInitPengukuranMap();
    
    // Load RTRW data
    if (mapInitialized && pengukuranMap) {
        await loadRTRWData();
        
        // Update map click handler
        pengukuranMap.off('click');
        pengukuranMap.on('click', originalMapOnClick);
        
        console.log('RTRW checking enabled');
    }
};

// Tambahkan tombol untuk toggle RTRW overlay
function addRTRWToggleButton() {
    if (!pengukuranMap) return;
    
    const RTRWControl = L.Control.extend({
        options: {
            position: 'topright'
        },
        onAdd: function(map) {
            const container = L.DomUtil.create('div', 'leaflet-bar leaflet-control');
            container.style.background = 'white';
            container.style.padding = '5px';
            container.innerHTML = `
                <button onclick="toggleRTRWOverlay()" 
                        style="border: none; background: white; cursor: pointer; padding: 5px 10px; font-size: 12px;"
                        title="Toggle RTRW Overlay">
                    <i class="fas fa-layer-group"></i> RTRW
                </button>
                <button onclick="checkAllCoordinatesRTRW()" 
                        style="border: none; background: white; cursor: pointer; padding: 5px 10px; font-size: 12px; border-top: 1px solid #ccc;"
                        title="Analisis Wilayah">
                    <i class="fas fa-search-location"></i> Cek
                </button>
            `;
            return container;
        }
    });
    
    pengukuranMap.addControl(new RTRWControl());
}

// Toggle visibility RTRW overlay
let rtrwOverlayVisible = true;
function toggleRTRWOverlay() {
    rtrwOverlayVisible = !rtrwOverlayVisible;
    
    rtrwLayers.forEach(layer => {
        if (rtrwOverlayVisible) {
            if (!pengukuranMap.hasLayer(layer)) {
                layer.addTo(pengukuranMap);
            }
        } else {
            if (pengukuranMap.hasLayer(layer)) {
                pengukuranMap.removeLayer(layer);
            }
        }
    });
    
    if (typeof toastr !== 'undefined') {
        toastr.info(`RTRW Overlay ${rtrwOverlayVisible ? 'ditampilkan' : 'disembunyikan'}`, '', {
            timeOut: 1500
        });
    }
}

// Export functions
window.loadRTRWData = loadRTRWData;
window.checkPointInRTRW = checkPointInRTRW;
window.showRTRWPopup = showRTRWPopup;
window.checkAllCoordinatesRTRW = checkAllCoordinatesRTRW;
window.toggleRTRWOverlay = toggleRTRWOverlay;
window.addRTRWToggleButton = addRTRWToggleButton;

// Auto-initialize when document ready
$(document).ready(function() {
    // Tambahkan tombol control setelah map initialized
    setTimeout(() => {
        if (pengukuranMap && mapInitialized) {
            addRTRWToggleButton();
        }
    }, 2000);
});

console.log('RTRW checking integration loaded');
</script>
<script>
// Update RTRW Summary setelah data loaded
function updateRTRWSummary() {
    const summaryDiv = document.getElementById('rtrwSummary');
    const legendDiv = document.getElementById('rtrwLegend');
    
    if (!summaryDiv || !legendDiv) return;
    
    if (rtrwData.length === 0) {
        summaryDiv.innerHTML = `
            <div class="text-center text-muted py-3">
                <i class="fas fa-exclamation-triangle fa-2x mb-2"></i>
                <p class="mb-0 small">Tidak ada data RTRW yang tersimpan</p>
                <a href="{{ route('rtrw.create') }}" class="btn btn-sm btn-primary mt-2">
                    <i class="fas fa-plus"></i> Tambah RTRW
                </a>
            </div>
        `;
        legendDiv.innerHTML = '<div class="col-12 text-center text-muted">Belum ada data RTRW</div>';
        return;
    }
    
    // Summary statistics
    summaryDiv.innerHTML = `
        <div class="row text-center">
            <div class="col-6 mb-2">
                <div style="background: linear-gradient(135deg, #4e73df, #224abe); padding: 15px; border-radius: 8px; color: white;">
                    <h3 class="mb-0">${rtrwData.length}</h3>
                    <small style="opacity: 0.9;">Total Wilayah</small>
                </div>
            </div>
            <div class="col-6 mb-2">
                <div style="background: linear-gradient(135deg, #1cc88a, #13855c); padding: 15px; border-radius: 8px; color: white;">
                    <h3 class="mb-0" id="activeOverlays">${rtrwOverlayVisible ? rtrwData.length : 0}</h3>
                    <small style="opacity: 0.9;">Overlay Aktif</small>
                </div>
            </div>
        </div>
        <div class="mt-2 small text-muted text-center">
            <i class="fas fa-info-circle"></i> Klik "Analisis" untuk pengecekan detail
        </div>
    `;
    
    // Legend items
    legendDiv.innerHTML = rtrwData.map(rtrw => `
        <div class="col-md-6 col-lg-4 mb-2">
            <div class="rtrw-legend-item" onclick="focusRTRW('${rtrw.id}')">
                <div class="rtrw-color-box" style="background-color: ${rtrw.warna};"></div>
                <div class="rtrw-legend-name">${rtrw.nama_rtrw}</div>
                <div class="rtrw-legend-code">${rtrw.warna}</div>
            </div>
        </div>
    `).join('');
}

// Focus map ke wilayah RTRW tertentu
function focusRTRW(rtrwId) {
    if (!pengukuranMap || !mapInitialized) {
        alert('Peta belum siap');
        return;
    }
    
    const rtrw = rtrwData.find(r => r.id == rtrwId);
    if (!rtrw) return;
    
    const rtrwLayer = rtrwLayers.find(layer => {
        const layerData = layer.toGeoJSON();
        return true; // Find matching layer
    });
    
    if (rtrwLayer) {
        const bounds = rtrwLayer.getBounds();
        pengukuranMap.fitBounds(bounds, {padding: [30, 30]});
        rtrwLayer.openPopup();
    }
}

// Override loadRTRWData untuk update summary
const originalLoadRTRWData = loadRTRWData;
loadRTRWData = async function() {
    await originalLoadRTRWData();
    updateRTRWSummary();
};

// Update summary saat toggle overlay
const originalToggleRTRWOverlay = toggleRTRWOverlay;
toggleRTRWOverlay = function() {
    originalToggleRTRWOverlay();
    const activeOverlaysEl = document.getElementById('activeOverlays');
    if (activeOverlaysEl) {
        activeOverlaysEl.textContent = rtrwOverlayVisible ? rtrwData.length : 0;
    }
};

// Auto-load summary saat halaman siap
$(document).ready(function() {
    setTimeout(() => {
        if (rtrwData.length > 0) {
            updateRTRWSummary();
        }
    }, 1500);
});
</script>
@endpush
