
@extends('admin-layouts.master')

@section('title', 'SP-MPT Baru')

@push('styles')
<style>
    body {
        background-color: #f8f9fa;
    }
    
    .header-gradient {
        background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        color: white;
        padding: 1rem;
        border-radius: 0;
    }
    
    .card {
        border: none;
        box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,0.075);
        margin-bottom: 1.5rem;
    }
    
    .section-title {
        font-size: 0.875rem;
        font-weight: 600;
        text-transform: uppercase;
        color: #495057;
        margin-bottom: 1rem;
        padding-bottom: 0.5rem;
        border-bottom: 2px solid #dee2e6;
    }
    
    .form-control:focus {
        border-color: #28a745;
        box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.25);
    }
    
    .required {
        color: #dc3545;
    }
    
    .upload-area {
        border: 2px dashed #dee2e6;
        border-radius: 0.25rem;
        padding: 2rem;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s;
        background-color: #fafafa;
    }
    
    .upload-area:hover {
        background-color: #e9ecef;
        border-color: #28a745;
    }
    
    .floating-buttons {
        position: fixed;
        bottom: 1rem;
        right: 1rem;
        z-index: 1000;
    }
    
    .btn-circle {
        width: 3rem;
        height: 3rem;
        border-radius: 50%;
        margin: 0.25rem;
        box-shadow: 0 0.25rem 0.5rem rgba(0,0,0,0.15);
    }
    
    #polygonMap {
        height: 450px;
        width: 100%;
        border: 1px solid #dee2e6;
        border-radius: 0.25rem;
    }
    
    .coordinate-input {
        font-size: 0.875rem;
    }
    
    @media print {
        .no-print {
            display: none !important;
        }
        
        .card {
            box-shadow: none;
            border: 1px solid #dee2e6;
        }
    }
</style>

<!-- Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="" />
@endpush

@section('content')
<div class="container-fluid">
    <!-- Header -->
    <div class="card">
        <div class="header-gradient">
            <h5 class="mb-0 font-weight-bold">SP-MPT BARU</h5>
            <small>Surat Pernyataan Melepaskan Penguasaan Tanah</small>
        </div>
    </div>

    <!-- Alerts -->
    @if(session('success'))
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle mr-2"></i>{{ session('success') }}
        <button type="button" class="close" data-dismiss="alert">
            <span>&times;</span>
        </button>
    </div>
    @endif

    @if($errors->any())
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <strong><i class="fas fa-exclamation-triangle mr-2"></i>Terdapat kesalahan:</strong>
        <ul class="mb-0 mt-2">
            @foreach($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
        <button type="button" class="close" data-dismiss="alert">
            <span>&times;</span>
        </button>
    </div>
    @endif

    <!-- Main Form -->
    <form method="POST" action="{{ route('sp-sipt.store') }}" enctype="multipart/form-data" id="formSpSipt">
        @csrf
        
        <div class="card">
            <div class="card-body">
                <!-- Nomor Surat -->
                <div class="form-group">
                    <label class="font-weight-bold">Nomor Surat:</label>
                    <input type="text" class="form-control bg-light" value="Otomatis saat disimpan" readonly>
                    <small class="text-muted">*Nomor surat akan digenerate otomatis</small>
                </div>
                <!-- PIHAK PERTAMA -->
                <h6 class="section-title">PIHAK PERTAMA</h6>
                
                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label>Nama <span class="required">*</span></label>
                        <input type="text" 
                               class="form-control @error('pemohon_nama') is-invalid @enderror" 
                               name="pemohon_nama" 
                               value="{{ old('pemohon_nama') }}"
                               placeholder="Masukkan nama lengkap"
                               required>
                        @error('pemohon_nama')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    
                    <div class="form-group col-md-6">
                        <label>Tempat/Tanggal Lahir</label>
                        <div class="input-group">
                            <input type="text" 
                                   class="form-control @error('pemohon_tempat_lahir') is-invalid @enderror" 
                                   name="pemohon_tempat_lahir" 
                                   value="{{ old('pemohon_tempat_lahir') }}"
                                   placeholder="Tempat lahir">
                            <input type="date" 
                                   class="form-control @error('pemohon_tanggal_lahir') is-invalid @enderror" 
                                   name="pemohon_tanggal_lahir" 
                                   value="{{ old('pemohon_tanggal_lahir') }}">
                        </div>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label>Nomor KTP <span class="required">*</span></label>
                        <input type="text" 
                               class="form-control @error('pemohon_nik') is-invalid @enderror" 
                               name="pemohon_nik" 
                               value="{{ old('pemohon_nik') }}"
                               placeholder="16 digit NIK"
                               maxlength="16"
                               pattern="[0-9]{16}"
                               required>
                        @error('pemohon_nik')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    
                    <div class="form-group col-md-6">
                        <label>Pekerjaan</label>
                        <input type="text" 
                               class="form-control @error('pemohon_pekerjaan') is-invalid @enderror" 
                               name="pemohon_pekerjaan" 
                               value="{{ old('pemohon_pekerjaan') }}"
                               placeholder="Masukkan pekerjaan">
                    </div>
                </div>

                <div class="form-group">
                    <label>Alamat <span class="required">*</span></label>
                    <textarea class="form-control @error('pemohon_alamat') is-invalid @enderror" 
                              name="pemohon_alamat" 
                              rows="2"
                              placeholder="Masukkan alamat lengkap"
                              required>{{ old('pemohon_alamat') }}</textarea>
                    @error('pemohon_alamat')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>

                <!-- PIHAK KEDUA -->
                <h6 class="section-title mt-4">PIHAK KEDUA</h6>
                
                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label>Nama <span class="required">*</span></label>
                        <input type="text" 
                               class="form-control @error('terlapor_nama') is-invalid @enderror" 
                               name="terlapor_nama" 
                               value="{{ old('terlapor_nama') }}"
                               placeholder="Masukkan nama lengkap"
                               required>
                        @error('terlapor_nama')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    
                    <div class="form-group col-md-6">
                        <label>Tempat/Tanggal Lahir</label>
                        <div class="input-group">
                            <input type="text" 
                                   class="form-control @error('terlapor_tempat_lahir') is-invalid @enderror" 
                                   name="terlapor_tempat_lahir" 
                                   value="{{ old('terlapor_tempat_lahir') }}"
                                   placeholder="Tempat lahir">
                            <input type="date" 
                                   class="form-control @error('terlapor_tanggal_lahir') is-invalid @enderror" 
                                   name="terlapor_tanggal_lahir" 
                                   value="{{ old('terlapor_tanggal_lahir') }}">
                        </div>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label>Nomor KTP</label>
                        <input type="text" 
                               class="form-control @error('terlapor_nik') is-invalid @enderror" 
                               name="terlapor_nik" 
                               value="{{ old('terlapor_nik') }}"
                               placeholder="16 digit NIK"
                               maxlength="16"
                               pattern="[0-9]{16}">
                        @error('terlapor_nik')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    
                    <div class="form-group col-md-6">
                        <label>Pekerjaan</label>
                        <input type="text" 
                               class="form-control @error('terlapor_pekerjaan') is-invalid @enderror" 
                               name="terlapor_pekerjaan" 
                               value="{{ old('terlapor_pekerjaan') }}"
                               placeholder="Masukkan pekerjaan">
                    </div>
                </div>

                <div class="form-group">
                    <label>Alamat</label>
                    <textarea class="form-control @error('terlapor_alamat') is-invalid @enderror" 
                              name="terlapor_alamat" 
                              rows="2"
                              placeholder="Masukkan alamat lengkap">{{ old('terlapor_alamat') }}</textarea>
                    @error('terlapor_alamat')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <!-- DATA TANAH -->
                <h6 class="section-title mt-4">DATA TANAH</h6>
                <div class="form-row">
                    <div class="form-group col-md-4">
                        <label>Ketua RT</label>
                        <input type="text" 
                               class="form-control @error('ketua_rt') is-invalid @enderror" 
                               name="ketua_rt" 
                               value="{{ old('ketua_rt') }}"
                               placeholder="">
                        @error('ketua_rt')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    <div class="form-group col-md-4">
                        <label>Nama RT</label>
                        <input type="text" 
                               class="form-control @error('nama_rt') is-invalid @enderror" 
                               name="nama_rt" 
                               value="{{ old('nama_rt') }}"
                               placeholder="">
                        @error('nama_rt')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    <div class="form-group col-md-4">
                        <label>Lokasi Tanah RT</label>
                        <input type="text" 
                               class="form-control @error('lokasi_tanah_rt') is-invalid @enderror" 
                               name="lokasi_tanah_rt" 
                               value="{{ old('lokasi_tanah_rt') }}"
                               placeholder="">
                        @error('lokasi_tanah_rt')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group col-md-4">
                        <label for="Kampung">Kampung/Kelurahan</label>
                        <select class="form-control select2" id="kampung_id" name="kampung_id" required>
                            <option value="">-- Pilih Kampung --</option>
                            @foreach($kampungs as $kampung)
                                <option value="{{ $kampung->id }}"
                                    {{ old('kampung_id') == $kampung->id ? 'selected' : '' }}>
                                    {{ $kampung->nama_kampung }}
                                </option>
                            @endforeach
                        </select>
                        @error('kampung_id')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                    </div>
                    <div class="form-group col-md-4">
                        <label for="Kecamatan">Kecamatan</label>
                        <select class="form-control select2" id="kecamatan_id" name="kecamatan_id" required>
                            <option value="">-- Pilih Kecamatan --</option>
                            @foreach($kecamatans as $kecamatan)
                                <option value="{{ $kecamatan->id }}"
                                    {{ old('kecamatan_id') == $kecamatan->id ? 'selected' : '' }}>
                                    {{ $kecamatan->nama_kecamatan }}
                                </option>
                            @endforeach
                        </select>
                        @error('kecamatan_id')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                    </div>
                    <div class="form-group col-md-4">
                        <label>Kota/Kabupaten</label>
                        <input type="text" 
                               class="form-control @error('lokasi_kota') is-invalid @enderror" 
                               name="lokasi_kota" 
                               value="{{ old('lokasi_kota') }}"
                               placeholder="Nama kota">
                        @error('lokasi_kota')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                </div>

                <!-- BATAS-BATAS TANAH -->
                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label>Utara</label>
                        <input type="text" 
                               class="form-control @error('batas_utara') is-invalid @enderror" 
                               name="batas_utara" 
                               value="{{ old('batas_utara') }}"
                               placeholder="Berbatasan dengan...">
                        @error('batas_utara')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    
                    <div class="form-group col-md-6">
                        <label>Timur</label>
                        <input type="text" 
                               class="form-control @error('batas_timur') is-invalid @enderror" 
                               name="batas_timur" 
                               value="{{ old('batas_timur') }}"
                               placeholder="Berbatasan dengan...">
                        @error('batas_timur')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label>Selatan</label>
                        <input type="text" 
                               class="form-control @error('batas_selatan') is-invalid @enderror" 
                               name="batas_selatan" 
                               value="{{ old('batas_selatan') }}"
                               placeholder="Berbatasan dengan...">
                        @error('batas_selatan')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    
                    <div class="form-group col-md-6">
                        <label>Barat</label>
                        <input type="text" 
                               class="form-control @error('batas_barat') is-invalid @enderror" 
                               name="batas_barat" 
                               value="{{ old('batas_barat') }}"
                               placeholder="Berbatasan dengan...">
                        @error('batas_barat')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                </div>

                <!-- PERNYATAAN -->
                <h6 class="section-title mt-4"></h6>
                
                <div class="form-group">
                    <div class="form-group col-md-4">
                        <label>Bukti (Kwitansi) Pembelian Tanggal</label>
                        <input type="date" 
                               class="form-control @error('tanggal_sertifikat') is-invalid @enderror" 
                               name="tanggal_sertifikat" 
                               value="{{ old('tanggal_sertifikat') }}"
                               placeholder="Berbatasan dengan...">
                        @error('tanggal_sertifikat')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                </div>

                <div class="form-group">
                    <div class="form-group col-md-4">
                        <label>Nomor dan Tanggal Surat Keterangan Penguasaan dan Pemilikan Bangunan/Tanaman Diatas Tanah Negara:</label>
                        <textarea name="nomor_tanggal_surat_penguasaan_tanah" class="form-control @error('nomor_tanggal_surat_penguasaan_tanah') is-invalid @enderror" id="" cols="30" rows="3">
                            {{ old('nomor_tanggal_surat_penguasaan_tanah') }}
                        </textarea>
                        @error('nomor_tanggal_surat_penguasaan_tanah')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <!-- UPLOAD DOKUMEN -->
                <h6 class="section-title mt-4">UPLOAD DOKUMEN</h6>
                
                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label>Upload KWITANSI (PDF/IMAGE)</label>
                        <div class="upload-area" onclick="document.getElementById('ktp_file').click()">
                            <i class="fas fa-cloud-upload-alt fa-3x text-muted mb-3"></i>
                            <p class="mb-1">Klik untuk upload file berformat PDF</p>
                            <small class="text-muted">Format: PDF • Maksimal: 5MB</small>
                            <input type="file" 
                                   id="ktp_file"
                                   name="kwitansi" 
                                   class="d-none"
                                   accept=".pdf,image/*"
                                   onchange="showFileInfo(this, 'ktp_preview')">
                            <div id="ktp_preview" class="mt-3"></div>
                        </div>
                        @error('kwitansi')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                    </div>
                    
                    <div class="form-group col-md-6">
                        <label>Upload Dokumen Pendukung</label>
                        <div class="upload-area" onclick="document.getElementById('template_file').click()">
                            <i class="fas fa-cloud-upload-alt fa-3x text-muted mb-3"></i>
                            <p class="mb-1">Klik untuk upload dokumen template</p>
                            <small class="text-muted">Format: PDF, DOC, DOCX • Maksimal: 10MB</small>
                            <input type="file" 
                                   id="template_file"
                                   name="dokumen_template" 
                                   class="d-none"
                                   accept=".pdf,.doc,.docx"
                                   onchange="showFileInfo(this, 'template_preview')">
                            <div id="template_preview" class="mt-3"></div>
                        </div>
                        @error('dokumen_template')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label>Peruntukan Bidang Tanah</label>
                        <input type="text" 
                               class="form-control @error('peruntukan_bidang_tanah') is-invalid @enderror" 
                               name="peruntukan_bidang_tanah" 
                               value="{{ old('peruntukan_bidang_tanah') }}"
                               placeholder="">
                        @error('peruntukan_bidang_tanah')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    
                    <div class="form-group col-md-6">
                        <label>Uang Ganti Kerugian/Santunan</label>
                        <input type="text" 
                               class="form-control @error('uang_ganti_kerugian') is-invalid @enderror" 
                               name="uang_ganti_kerugian" 
                               value="{{ old('uang_ganti_kerugian') }}"
                               placeholder="">
                        @error('uang_ganti_kerugian')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <!-- KOORDINAT POLYGON Section -->
                <h6 class="section-title mt-4">KOORDINAT POLYGON TANAH</h6>

                <div class="row">
                    <div class="col-lg-5">
                        <!-- Coordinate Input Table -->
                        <div class="card border-primary mb-3">
                            <div class="card-header bg-primary text-white">
                                <h6 class="mb-0">Input Koordinat</h6>
                            </div>
                            <div class="card-body" style="max-height: 400px; overflow-y: auto;">
                                <table class="table table-sm">
                                    <thead class="bg-light sticky-top">
                                        <tr>
                                            <th width="10%">#</th>
                                            <th width="35%">Latitude</th>
                                            <th width="35%">Longitude</th>
                                            <th width="20%" class="text-center">Aksi</th>
                                        </tr>
                                    </thead>
                                    <tbody id="coordinatesList">
                                        <!-- Default 3 rows -->
                                        <tr id="coord-1">
                                            <td class="align-middle font-weight-bold">1</td>
                                            <td>
                                                <input type="text" class="form-control form-control-sm" 
                                                       name="lat[1]" id="lat_1" 
                                                       placeholder="-1.xxxxxx"
                                                       onchange="updateMapPolygon()">
                                            </td>
                                            <td>
                                                <input type="text" class="form-control form-control-sm" 
                                                       name="lng[1]" id="lng_1" 
                                                       placeholder="116.xxxxxx"
                                                       onchange="updateMapPolygon()">
                                            </td>
                                            <td class="text-center">
                                                <button type="button" class="btn btn-danger btn-sm" 
                                                        onclick="removeCoordinate(1)" title="Hapus">
                                                    <i class="fas fa-times"></i>
                                                </button>
                                            </td>
                                        </tr>
                                        <tr id="coord-2">
                                            <td class="align-middle font-weight-bold">2</td>
                                            <td>
                                                <input type="text" class="form-control form-control-sm" 
                                                       name="lat[2]" id="lat_2" 
                                                       placeholder="-1.xxxxxx"
                                                       onchange="updateMapPolygon()">
                                            </td>
                                            <td>
                                                <input type="text" class="form-control form-control-sm" 
                                                       name="lng[2]" id="lng_2" 
                                                       placeholder="116.xxxxxx"
                                                       onchange="updateMapPolygon()">
                                            </td>
                                            <td class="text-center">
                                                <button type="button" class="btn btn-danger btn-sm" 
                                                        onclick="removeCoordinate(2)" title="Hapus">
                                                    <i class="fas fa-times"></i>
                                                </button>
                                            </td>
                                        </tr>
                                        <tr id="coord-3">
                                            <td class="align-middle font-weight-bold">3</td>
                                            <td>
                                                <input type="text" class="form-control form-control-sm" 
                                                       name="lat[3]" id="lat_3" 
                                                       placeholder="-1.xxxxxx"
                                                       onchange="updateMapPolygon()">
                                            </td>
                                            <td>
                                                <input type="text" class="form-control form-control-sm" 
                                                       name="lng[3]" id="lng_3" 
                                                       placeholder="116.xxxxxx"
                                                       onchange="updateMapPolygon()">
                                            </td>
                                            <td class="text-center">
                                                <button type="button" class="btn btn-danger btn-sm" 
                                                        onclick="removeCoordinate(3)" title="Hapus">
                                                    <i class="fas fa-times"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                                
                                <button type="button" class="btn btn-primary btn-sm btn-block" onclick="addCoordinate()">
                                    <i class="fas fa-plus"></i> Tambah Koordinat
                                </button>
                                
                                <!-- Hidden input for JSON data -->
                                <input type="hidden" name="coordinates_data" id="coordinates_data" value="{{ old('coordinates_data') }}">
                                <input type="hidden" name="map_image_data" id="map_image_data" value="{{ old('map_image_data') }}">
                            </div>
                        </div>
                        
                        <!-- Area Information -->
                        <div class="card border-success">
                            <div class="card-header bg-success text-white">
                                <h6 class="mb-0">Informasi Area</h6>
                            </div>
                            <div class="card-body">
                                <div class="row text-center">
                                    <div class="col-6">
                                        <div class="h4 text-success mb-0" id="calculatedArea">0 m²</div>
                                        <small class="text-muted">Luas Terukur</small>
                                    </div>
                                    <div class="col-6">
                                        <div class="h4 text-info mb-0" id="coordinateCount">0</div>
                                        <small class="text-muted">Titik Koordinat</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-lg-7">
                        <!-- Map with Polygon -->
                        <div class="card border-info">
                            <div class="card-header bg-info text-white d-flex justify-content-between">
                                <h6 class="mb-0">Peta Polygon</h6>
                                <div class="btn-group btn-group-sm">
                                    <button type="button" class="btn btn-light btn-sm" onclick="centerMap()">
                                        <i class="fas fa-crosshairs"></i> Center
                                    </button>
                                    <button type="button" class="btn btn-warning btn-sm" onclick="captureMap()">
                                        <i class="fas fa-camera"></i> Capture
                                    </button>
                                </div>
                            </div>
                            <div class="card-body p-0">
                                <div id="polygonMap" style="height: 450px;"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Floating Buttons -->
        <div class="floating-buttons no-print">
            <button type="submit" class="btn btn-success btn-circle" title="Simpan">
                <i class="fas fa-save"></i>
            </button>
            <button type="button" class="btn btn-secondary btn-circle" onclick="window.location.href='{{ route('sp-sipt.index') }}'" title="Kembali">
                <i class="fas fa-arrow-left"></i>
            </button>
        </div>
    </form>
</div>
@endsection

@push('scripts')
<!-- Leaflet JS -->
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
<!-- jQuery and Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
<!-- Select2 JS -->
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

<script>
// Global variables
let map;
let polygon = null;
let markers = [];
let coordinateCount = 3;
let coordinates = [];
let hasCaptured = false; // Flag to track if auto-capture has occurred

// Initialize map with Leaflet layers
function initMap() {
    try {
        // Ensure map container exists
        const mapContainer = document.getElementById('polygonMap');
        if (!mapContainer) {
            console.error('Map container not found');
            return;
        }

        // Create map centered on Balikpapan
        map = L.map('polygonMap', {
            center: [-1.2379, 116.8529],
            zoom: 13,
            layers: []
        });

        // Define base layers
        const baseLayers = {
            'OpenStreetMap': L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
                maxZoom: 19
            }),
            'Esri World Imagery': L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
                attribution: '© <a href="https://www.esri.com/">Esri</a>, Maxar, GeoEye, Earthstar Geographics',
                maxZoom: 19
            }),
            'Stamen Terrain': L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/terrain/{z}/{x}/{y}{r}.jpg', {
                attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> &mdash; Map data © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
                subdomains: 'abcd',
                maxZoom: 18
            })
        };

        // Set default layer
        baseLayers['OpenStreetMap'].addTo(map);

        // Add layer control
        L.control.layers(baseLayers, null, {
            position: 'topright',
            collapsed: false
        }).addTo(map);

        // Add click event to map
        map.on('click', function(e) {
            const lat = e.latlng.lat.toFixed(6);
            const lng = e.latlng.lng.toFixed(6);
            
            if (confirm(`Tambah koordinat?\nLat: ${lat}\nLng: ${lng}`)) {
                addCoordinateWithValues(lat, lng);
            }
        });

        // Invalidate size to ensure map renders correctly
        setTimeout(() => {
            map.invalidateSize();
        }, 100);

        // Load existing coordinates if available
        loadExistingCoordinates();
    } catch (error) {
        console.error('Error initializing map:', error);
        alert('Gagal memuat peta. Silakan coba lagi.');
    }
}

// Update map polygon from coordinates
function updateMapPolygon() {
    try {
        // Clear existing
        if (polygon) {
            map.removeLayer(polygon);
        }
        markers.forEach(marker => map.removeLayer(marker));
        markers = [];
        
        // Get coordinates from inputs
        coordinates = [];
        const rows = document.querySelectorAll('#coordinatesList tr');
        
        rows.forEach((row, index) => {
            const coordId = row.id.split('-')[1];
            const latInput = document.getElementById(`lat_${coordId}`);
            const lngInput = document.getElementById(`lng_${coordId}`);
            
            if (!latInput || !lngInput) return;

            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: #28a745; color: white; width: 25px; height: 25px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; border: 2px solid white;">${index + 1}</div>`,
                        iconSize: [25, 25],
                        iconAnchor: [12, 12]
                    })
                }).addTo(map);
                
                markers.push(marker);
            }
        });
        
        // Update coordinate count
        document.getElementById('coordinateCount').textContent = coordinates.length;
        
        // Draw polygon if we have at least 3 coordinates
        if (coordinates.length >= 3) {
            polygon = L.polygon(coordinates.map(c => [c.lat, c.lng]), {
                color: '#ff0000',
                fillColor: '#ffff00',
                fillOpacity: 0.3,
                weight: 2
            }).addTo(map);
            
            // Calculate and display area
            calculateArea();
            
            // Fit map to polygon bounds
            map.fitBounds(polygon.getBounds());

            // Auto-capture map when exactly 3 valid coordinates are entered
            if (coordinates.length === 3 && !hasCaptured) {
                captureMap();
                hasCaptured = true; // Prevent repeated auto-captures
            }
        } else {
            // Reset area and capture flag if insufficient coordinates
            document.getElementById('calculatedArea').textContent = '0 m²';
            hasCaptured = false; // Allow auto-capture again if coordinates drop below 3
        }
        
        // Update hidden input
        document.getElementById('coordinates_data').value = JSON.stringify(coordinates);
    } catch (error) {
        console.error('Error updating polygon:', error);
    }
}

// Add new coordinate row
function addCoordinate() {
    coordinateCount++;
    const tbody = document.getElementById('coordinatesList');
    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" 
                   name="lat[${coordinateCount}]" id="lat_${coordinateCount}" 
                   placeholder="-1.xxxxxx"
                   onchange="updateMapPolygon()">
        </td>
        <td>
            <input type="text" class="form-control form-control-sm" 
                   name="lng[${coordinateCount}]" id="lng_${coordinateCount}" 
                   placeholder="116.xxxxxx"
                   onchange="updateMapPolygon()">
        </td>
        <td class="text-center">
            <button type="button" class="btn btn-danger btn-sm" 
                    onclick="removeCoordinate(${coordinateCount})" title="Hapus">
                <i class="fas fa-times"></i>
            </button>
        </td>
    `;
    tbody.appendChild(newRow);
}

// Add coordinate with values
function addCoordinateWithValues(lat, lng) {
    coordinateCount++;
    const tbody = document.getElementById('coordinatesList');
    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" 
                   name="lat[${coordinateCount}]" id="lat_${coordinateCount}" 
                   value="${lat}"
                   onchange="updateMapPolygon()">
        </td>
        <td>
            <input type="text" class="form-control form-control-sm" 
                   name="lng[${coordinateCount}]" id="lng_${coordinateCount}" 
                   value="${lng}"
                   onchange="updateMapPolygon()">
        </td>
        <td class="text-center">
            <button type="button" class="btn btn-danger btn-sm" 
                    onclick="removeCoordinate(${coordinateCount})" title="Hapus">
                <i class="fas fa-times"></i>
            </button>
        </td>
    `;
    tbody.appendChild(newRow);
    
    // Update map
    updateMapPolygon();
}

// Remove coordinate row
function removeCoordinate(id) {
    if (confirm('Hapus koordinat ini?')) {
        const row = document.getElementById(`coord-${id}`);
        if (row) {
            row.remove();
            
            // Re-number rows
            const rows = document.querySelectorAll('#coordinatesList tr');
            rows.forEach((row, index) => {
                row.querySelector('td:first-child').textContent = index + 1;
            });
            
            updateMapPolygon();
        }
    }
}

// Calculate polygon area (Shoelace formula)
function calculateArea() {
    if (coordinates.length < 3) {
        document.getElementById('calculatedArea').textContent = '0 m²';
        return;
    }
    
    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)
        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;
        
        document.getElementById('calculatedArea').textContent = 
            areaInSquareMeters.toLocaleString('id-ID', {maximumFractionDigits: 2}) + ' m²';
    } catch (error) {
        console.error('Error calculating area:', error);
        document.getElementById('calculatedArea').textContent = 'Error';
    }
}

// Center map on polygon
function centerMap() {
    try {
        if (polygon) {
            map.fitBounds(polygon.getBounds());
        } else if (coordinates.length > 0) {
            map.setView([coordinates[0].lat, coordinates[0].lng], 15);
        } else {
            map.setView([-1.2379, 116.8529], 13);
        }
    } catch (error) {
        console.error('Error centering map:', error);
    }
}

// Capture map as image
function captureMap() {
    try {
        // Create canvas
        const canvas = document.createElement('canvas');
        canvas.width = 800;
        canvas.height = 600;
        const ctx = canvas.getContext('2d');
        
        // Draw background
        ctx.fillStyle = '#f0f0f0';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        
        if (coordinates.length >= 3) {
            // Calculate bounds for drawing
            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 padding = 50;
            const width = canvas.width - 2 * padding;
            const height = canvas.height - 2 * padding;
            
            // Scale coordinates to canvas
            function scaleToCanvas(lat, lng) {
                const x = padding + ((lng - minLng) / (maxLng - minLng)) * width;
                const y = padding + ((maxLat - lat) / (maxLat - minLat)) * height;
                return {x, y};
            }
            
            // Draw polygon
            ctx.fillStyle = 'rgba(255, 255, 0, 0.3)';
            ctx.strokeStyle = '#ff0000';
            ctx.lineWidth = 2;
            
            ctx.beginPath();
            coordinates.forEach((coord, i) => {
                const point = scaleToCanvas(coord.lat, coord.lng);
                if (i === 0) {
                    ctx.moveTo(point.x, point.y);
                } else {
                    ctx.lineTo(point.x, point.y);
                }
            });
            ctx.closePath();
            ctx.fill();
            ctx.stroke();
            
            // Draw markers
            coordinates.forEach((coord, i) => {
                const point = scaleToCanvas(coord.lat, coord.lng);
                
                // Draw circle
                ctx.fillStyle = '#28a745';
                ctx.strokeStyle = '#ffffff';
                ctx.lineWidth = 2;
                ctx.beginPath();
                ctx.arc(point.x, point.y, 12, 0, 2 * Math.PI);
                ctx.fill();
                ctx.stroke();
                
                // Draw number
                ctx.fillStyle = '#ffffff';
                ctx.font = 'bold 12px Arial';
                ctx.textAlign = 'center';
                ctx.textBaseline = 'middle';
                ctx.fillText((i + 1).toString(), point.x, point.y);
            });
            
            // Add title
            ctx.fillStyle = '#000000';
            ctx.font = 'bold 16px Arial';
            ctx.textAlign = 'center';
            ctx.fillText('PETA POLYGON TANAH', canvas.width / 2, 25);
        }
        
        // Save as base64
        const imageData = canvas.toDataURL('image/png');
        document.getElementById('map_image_data').value = imageData;
        
        alert('Peta berhasil di-capture!');
    } catch (error) {
        console.error('Error capturing map:', error);
        alert('Gagal capture peta. Silakan coba lagi.');
    }
}

// Load existing coordinates if editing
function loadExistingCoordinates() {
    try {
        @if(isset($spSipt) && $spSipt->coordinates)
            const existingCoords = @json($spSipt->coordinates_array);
            
            // Clear default rows
            document.getElementById('coordinatesList').innerHTML = '';
            coordinateCount = 0;
            
            // Add existing coordinates
            existingCoords.forEach(coord => {
                coordinateCount++;
                const tbody = document.getElementById('coordinatesList');
                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" 
                               name="lat[${coordinateCount}]" id="lat_${coordinateCount}" 
                               value="${coord.lat}"
                               onchange="updateMapPolygon()">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="lng[${coordinateCount}]" id="lng_${coordinateCount}" 
                               value="${coord.lng}"
                               onchange="updateMapPolygon()">
                    </td>
                    <td class="text-center">
                        <button type="button" class="btn btn-danger btn-sm" 
                                onclick="removeCoordinate(${coordinateCount})" title="Hapus">
                            <i class="fas fa-times"></i>
                        </button>
                    </td>
                `;
                tbody.appendChild(newRow);
            });
            
            // Update map
            setTimeout(updateMapPolygon, 500);
        @endif
    } catch (error) {
        console.error('Error loading existing coordinates:', error);
    }
}

// File upload handler
function showFileInfo(input, previewId) {
    try {
        const file = input.files[0];
        if (file) {
            const fileName = file.name;
            const fileSize = (file.size / 1024 / 1024).toFixed(2);
            
            $('#' + previewId).html(`
                <div class="alert alert-success">
                    <i class="fas fa-file-pdf mr-2"></i>
                    <strong>${fileName}</strong> (${fileSize} MB)
                    <button type="button" class="close" onclick="clearFile('${input.id}', '${previewId}')">
                        <span>&times;</span>
                    </button>
                </div>
            `);
        }
    } catch (error) {
        console.error('Error handling file upload:', error);
    }
}

// Clear file input
function clearFile(inputId, previewId) {
    try {
        $('#' + inputId).val('');
        $('#' + previewId).html('');
    } catch (error) {
        console.error('Error clearing file input:', error);
    }
}

// Form validation
function initializeValidation() {
    try {
        // Initialize Select2 for dropdowns
        $('.select2').select2();

        // NIK validation
        $('input[name="pemohon_nik"], input[name="terlapor_nik"]').on('input', function() {
            this.value = this.value.replace(/[^0-9]/g, '').substring(0, 16);
        });

        // Form submit validation
        $('#formSpSipt').on('submit', function(e) {
            let isValid = true;
            const errors = [];

            // Check required fields
            const requiredFields = {
                'pemohon_nama': 'Nama Pihak Pertama',
                'pemohon_nik': 'NIK Pihak Pertama', 
                'pemohon_alamat': 'Alamat Pihak Pertama',
                'terlapor_nama': 'Nama Pihak Kedua',
                'kampung_id': 'Kampung/Kelurahan',
                'kecamatan_id': 'Kecamatan'
            };

            $.each(requiredFields, function(field, label) {
                const value = $(`[name="${field}"]`).val();
                if (!value || value.trim() === '') {
                    errors.push(`${label} harus diisi`);
                    $(`[name="${field}"]`).addClass('is-invalid');
                    isValid = false;
                }
            });

            // Check NIK length
            const nik = $('input[name="pemohon_nik"]').val();
            if (nik && nik.length !== 16) {
                errors.push('NIK Pihak Pertama harus 16 digit');
                $('input[name="pemohon_nik"]').addClass('is-invalid');
                isValid = false;
            }

            const terlaporNik = $('input[name="terlapor_nik"]').val();
            if (terlaporNik && terlaporNik.length !== 16) {
                errors.push('NIK Pihak Kedua harus 16 digit');
                $('input[name="terlapor_nik"]').addClass('is-invalid');
                isValid = false;
            }

            // Check coordinates
            if (coordinates.length < 3) {
                errors.push('Minimal 3 koordinat diperlukan untuk membentuk polygon');
                isValid = false;
            }

            if (!isValid) {
                e.preventDefault();
                
                // Show errors
                if (errors.length > 0) {
                    let errorMsg = '<ul class="mb-0">';
                    errors.forEach(error => {
                        errorMsg += `<li>${error}</li>`;
                    });
                    errorMsg += '</ul>';
                    
                    $('#errorModal').remove();
                    $('body').append(`
                        <div class="modal fade" id="errorModal" tabindex="-1">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <div class="modal-header bg-danger text-white">
                                        <h5 class="modal-title">Validasi Gagal</h5>
                                        <button type="button" class="close text-white" data-dismiss="modal">
                                            <span>&times;</span>
                                        </button>
                                    </div>
                                    <div class="modal-body">
                                        ${errorMsg}
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `);
                    $('#errorModal').modal('show');
                }
                
                // Scroll to first invalid field
                const firstInvalid = $('.is-invalid').first();
                if (firstInvalid.length) {
                    $('html, body').animate({
                        scrollTop: firstInvalid.offset().top - 100
                    }, 500);
                }
            }
        });

        // Remove invalid class on input
        $('input, textarea, select').on('input change', function() {
            $(this).removeClass('is-invalid');
        });
    } catch (error) {
        console.error('Error initializing validation:', error);
    }
}

// Utility functions
function scrollToBottom() {
    try {
        $('html, body').animate({
            scrollTop: $(document).height()
        }, 1000);
    } catch (error) {
        console.error('Error scrolling to bottom:', error);
    }
}

// Initialize everything when DOM is ready
$(document).ready(function() {
    try {
        initMap();
        initializeValidation();
        $('[data-toggle="tooltip"]').tooltip();
    } catch (error) {
        console.error('Error during initialization:', error);
        alert('Terjadi kesalahan saat memuat halaman. Silakan coba lagi.');
    }
});
</script>
@endpush
