
{{-- resources/views/peninjauan/partials/tab-pengukuran.blade.php --}}

<!-- Pengukuran Tab -->
<div class="tab-pane fade" id="pengukuran" role="tabpanel">
    <div class="card">
        <div class="card-header">
            Pengukuran, Persetujuan, Koordinat
        </div>
        <div class="card-body">
            <!-- BA Pengukuran Section -->
            <h5 class="section-title">BA Pengukuran Bidang Tanah</h5>
            
            <div class="row mb-3">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="nomor_ba_pengukuran">Nomor BA Pengukuran Bidang Tanah</label>
                        <input type="text" class="form-control" id="nomor_ba_pengukuran" name="nomor_ba_pengukuran" value="{{ old('nomor_ba_pengukuran') }}" placeholder="Nomor BA Pengukuran">
                        @error('nomor_ba_pengukuran')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="tanggal_pengukuran">Tanggal Pengukuran</label>
                        <input type="date" class="form-control" id="tanggal_pengukuran" name="tanggal_pengukuran" value="{{ old('tanggal_pengukuran') }}">
                        @error('tanggal_pengukuran')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                    </div>
                </div>
            </div>

            <!-- Keterangan Pengukuran -->
            <h5 class="section-title">Keterangan Pengukuran</h5>
            
            <div class="row mb-3">
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="surat_tugas_nomor">Surat Tugas Nomor</label>
                        <input type="text" class="form-control" id="surat_tugas_nomor" name="surat_tugas_nomor" value="{{ old('surat_tugas_nomor') }}" placeholder="Nomor surat tugas">
                        @error('surat_tugas_nomor')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="surat_tugas_tanggal">Tanggal</label>
                        <input type="date" class="form-control" id="surat_tugas_tanggal" name="surat_tugas_tanggal" value="{{ old('surat_tugas_tanggal') }}">
                        @error('surat_tugas_tanggal')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="petugas_ukur">Petugas Ukur</label>
                        <input type="text" class="form-control" id="petugas_ukur" name="petugas_ukur" value="{{ old('petugas_ukur') }}" placeholder="Nama petugas ukur">
                        @error('petugas_ukur')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                    </div>
                </div>
            </div>

            <!-- BA Persetujuan -->
            <h5 class="section-title">BA Persetujuan Pengukuran Tanah</h5>
            
            <div class="row mb-3">
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="nomor_ba_persetujuan">Nomor BA Persetujuan Pengukuran Tanah</label>
                        <input type="text" class="form-control" id="nomor_ba_persetujuan" name="nomor_ba_persetujuan" value="{{ old('nomor_ba_persetujuan') }}" placeholder="Nomor BA Persetujuan">
                        @error('nomor_ba_persetujuan')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="tanggal_permohonan">Tanggal Permohonan</label>
                        <input type="date" class="form-control" id="tanggal_permohonan" name="tanggal_permohonan" value="{{ old('tanggal_permohonan') }}">
                        @error('tanggal_permohonan')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="ukuran_patok">Ukuran Patok (cm)</label>
                        <div class="input-group">
                            <input type="number" class="form-control" id="ukuran_patok" name="ukuran_patok" value="{{ old('ukuran_patok') }}" placeholder="Ukuran" style="width: 150px;" step="0.01">
                            <div class="input-group-append">
                                <span class="input-group-text">cm</span>
                            </div>
                        </div>
                        @error('ukuran_patok')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                    </div>
                </div>
            </div>

            <!-- Batas Koordinat dan Peta -->
            <h5 class="section-title">Batas Koordinat dan Peta</h5>
            
            <div class="row mb-3">
                <div class="col-12">
                    <div class="form-group">
                        <label>Batas Koordinat:</label>
                        <div class="d-flex align-items-center flex-wrap">
                            <label class="mr-2 mb-0">Sistem Koordinat UTM</label>
                            <input type="text" class="form-control mr-2" name="sistem_koordinat" value="{{ old('sistem_koordinat', 'UTM') }}" readonly style="width: 100px; background: #f3f4f6;">
                            <label class="mr-2 mb-0">cm X:</label>
                            <input type="text" class="form-control mr-2" id="cm_x" name="cm_x" value="{{ old('cm_x') }}" placeholder="X" style="width: 50px;">
                            <label class="mr-2 mb-0">Tanggal Pengukuran:</label>
                            <input type="date" class="form-control" id="tanggal_pengukuran_koordinat" name="tanggal_pengukuran_koordinat" value="{{ old('tanggal_pengukuran_koordinat') }}">
                        </div>
                        @error('cm_x')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                        @error('tanggal_pengukuran_koordinat')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                    </div>
                </div>
            </div>

            <!-- Map Section -->
            <div class="row mb-3">
                <!-- Coordinates Table -->
                <div class="col-lg-12">
                    <h6 class="mb-2">Data Koordinat:</h6>
                    <div class="card bg-light mb-3" style="max-height: 400px; overflow-y: auto;">
                        <div class="card-body p-2">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th scope="col">No</th>
                                        <th scope="col">Latitude</th>
                                        <th scope="col">Longitude</th>
                                        <th scope="col" class="text-center">Aksi</th>
                                    </tr>
                                </thead>
                                <tbody id="coordinatesList">
                                    <tr id="coord-1">
                                        <td>1</td>
                                        <td><input type="text" class="form-control form-control-sm" id="lat_1" name="lat[1]" value="-0.517626" onchange="updateMap()"></td>
                                        <td><input type="text" class="form-control form-control-sm" id="lng_1" name="lng[1]" value="117.0159746" onchange="updateMap()"></td>
                                        <td class="text-center">
                                            <button type="button" onclick="removeCoordinate(1)" class="btn btn-danger btn-sm">×</button>
                                        </td>
                                    </tr>
                                    <tr id="coord-2">
                                        <td>2</td>
                                        <td><input type="text" class="form-control form-control-sm" id="lat_2" name="lat[2]" value="-0.517654" onchange="updateMap()"></td>
                                        <td><input type="text" class="form-control form-control-sm" id="lng_2" name="lng[2]" value="117.0159593" onchange="updateMap()"></td>
                                        <td class="text-center">
                                            <button type="button" onclick="removeCoordinate(2)" class="btn btn-danger btn-sm">×</button>
                                        </td>
                                    </tr>
                                    <tr id="coord-3">
                                        <td>3</td>
                                        <td><input type="text" class="form-control form-control-sm" id="lat_3" name="lat[3]" value="-0.517523" onchange="updateMap()"></td>
                                        <td><input type="text" class="form-control form-control-sm" id="lng_3" name="lng[3]" value="117.0159559" onchange="updateMap()"></td>
                                        <td class="text-center">
                                            <button type="button" onclick="removeCoordinate(3)" class="btn btn-danger btn-sm">×</button>
                                        </td>
                                    </tr>
                                    <tr id="coord-4">
                                        <td>4</td>
                                        <td><input type="text" class="form-control form-control-sm" id="lat_4" name="lat[4]" value="-0.517490" onchange="updateMap()"></td>
                                        <td><input type="text" class="form-control form-control-sm" id="lng_4" name="lng[4]" value="117.0159667" onchange="updateMap()"></td>
                                        <td class="text-center">
                                            <button type="button" onclick="removeCoordinate(4)" class="btn btn-danger btn-sm">×</button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                            <button type="button" onclick="addCoordinate()" class="btn btn-primary btn-sm btn-block mt-2">+ Tambah Koordinat</button>
                        </div>
                    </div>
                    <p class="text-muted small">Batas koordinat pertama sama dengan koordinat terakhir (Polygon tertutup)</p>
                </div>

                <!-- Leaflet Map -->
                <div class="col-lg-12">
                    <h6 class="mb-2">Peta Lokasi:</h6>
                    <div id="pengukuranMap" style="height: 400px; border: 1px solid #e5e7eb; border-radius: 6px;"></div>
                    <div class="d-flex mt-2">
                        <button type="button" onclick="centerMap()" class="btn btn-secondary btn-sm mr-2">🎯 Center Map</button>
                        <button type="button" onclick="calculatePolygonArea()" class="btn btn-primary btn-sm">📐 Hitung Luas</button>
                    </div>
                </div>
            </div>
        </div>
        <!-- Form Actions -->
        <div class="card-footer d-flex justify-content-between">
            <button type="button" class="btn btn-secondary" onclick="previousTab()">← Sebelumnya</button>
            <div>
                <button type="button" class="btn btn-secondary mr-2" onclick="saveDraft()">💾 Simpan Draft</button>
                <button type="button" class="btn btn-primary" onclick="nextTab()">Selanjutnya →</button>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
    // Map variables for Pengukuran tab
    let pengukuranMap = null;
    let pengukuranPolygon = null;
    let pengukuranMarkers = [];
    let coordinateCount = 4;
    let coordinates = [];

    // Initialize map when tab is shown
    function initPengukuranMap() {
        if (!pengukuranMap) {
            // Initialize map centered on East Kalimantan
            pengukuranMap = L.map('pengukuranMap').setView([-0.5176, 117.0159], 18);
            
            // Add tile layer
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '© OpenStreetMap contributors',
                maxZoom: 20
            }).addTo(pengukuranMap);
            
            // Initial update
            updateMap();
        }
    }

    // Update map with coordinates from table
    function updateMap() {
        if (!pengukuranMap) return;
        
        // Clear existing markers and polygon
        pengukuranMarkers.forEach(marker => pengukuranMap.removeLayer(marker));
        pengukuranMarkers = [];
        
        if (pengukuranPolygon) {
            pengukuranMap.removeLayer(pengukuranPolygon);
        }
        
        // Get coordinates from inputs
        coordinates = [];
        const rows = document.querySelectorAll('#coordinatesList tr');
        
        rows.forEach((row, index) => {
            const latInput = row.querySelector(`#lat_${row.id.split('-')[1]}`);
            const lngInput = row.querySelector(`#lng_${row.id.split('-')[1]}`);
            
            if (latInput && lngInput && latInput.value && lngInput.value) {
                const lat = parseFloat(latInput.value);
                const lng = parseFloat(lngInput.value);
                
                if (!isNaN(lat) && !isNaN(lng)) {
                    coordinates.push({lat: lat, lng: lng});
                    
                    // Add numbered marker
                    const marker = L.marker([lat, lng], {
                        icon: L.divIcon({
                            className: 'custom-div-icon',
                            html: `<div style="background: #dc2626; color: white; width: 24px; height: 24px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 11px; font-weight: bold; border: 2px solid white; box-shadow: 0 2px 4px rgba(0,0,0,0.3);">${index + 1}</div>`,
                            iconSize: [24, 24],
                            iconAnchor: [12, 12]
                        })
                    }).addTo(pengukuranMap);
                    
                    pengukuranMarkers.push(marker);
                }
            }
        });
        
        // Draw polygon if we have at least 3 coordinates
        if (coordinates.length >= 3) {
            const latlngs = coordinates.map(coord => [coord.lat, coord.lng]);
            pengukuranPolygon = L.polygon(latlngs, {
                color: '#dc2626',
                fillColor: '#dc2626',
                fillOpacity: 0.2,
                weight: 2
            }).addTo(pengukuranMap);
            
            // Fit map to polygon bounds
            pengukuranMap.fitBounds(pengukuranPolygon.getBounds());
        }
        
        // Update hidden input
        document.getElementById('coordinates_input').value = JSON.stringify(coordinates);
    }

    // Add new coordinate row
    function addCoordinate() {
        coordinateCount++;
        const tbody = document.getElementById('coordinatesList');
        const newRow = document.createElement('tr');
        newRow.id = `coord-${coordinateCount}`;
        newRow.innerHTML = `
            <td>${coordinateCount}</td>
            <td><input type="text" class="form-control form-control-sm" id="lat_${coordinateCount}" name="lat[${coordinateCount}]" placeholder="Latitude" onchange="updateMap()"></td>
            <td><input type="text" class="form-control form-control-sm" id="lng_${coordinateCount}" name="lng[${coordinateCount}]" placeholder="Longitude" onchange="updateMap()"></td>
            <td class="text-center">
                <button type="button" onclick="removeCoordinate(${coordinateCount})" class="btn btn-danger btn-sm">×</button>
            </td>
        `;
        tbody.appendChild(newRow);
    }

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

    // Center map on polygon
    function centerMap() {
        if (pengukuranPolygon) {
            pengukuranMap.fitBounds(pengukuranPolygon.getBounds());
        }
    }

    // Calculate polygon area
    function calculatePolygonArea() {
        if (coordinates.length < 3) {
            alert('Minimal 3 titik koordinat diperlukan untuk menghitung luas');
            return;
        }
        
        // Calculate area using Shoelace formula
        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
        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;
        
        alert(`Luas area: ${areaInSquareMeters.toFixed(2)} m²`);
    }
</script>
@endpush
