<?php $__env->startSection('title', 'Edit SP-MPT'); ?>

<?php $__env->startPush('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;
    }

    .file-link {
        color: #28a745;
        text-decoration: none;
    }

    .file-link:hover {
        text-decoration: underline;
    }

    @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="" />
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<!-- Proj4js for UTM conversion -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.7.4/proj4.js"></script>
<?php $__env->stopPush(); ?>

<?php $__env->startSection('content'); ?>
<div class="container-fluid">
    <!-- Header -->
    <div class="card">
        <div class="header-gradient">
            <h5 class="mb-0 font-weight-bold">EDIT SP-MPT</h5>
            <small>Surat Pernyataan Melepaskan Penguasaan Tanah</small>
        </div>
    </div>

    <!-- Alerts -->
    <?php if(session('success')): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle mr-2"></i><?php echo e(session('success')); ?>

        <button type="button" class="close" data-dismiss="alert">
            <span>&times;</span>
        </button>
    </div>
    <?php endif; ?>

    <?php 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">
            <?php $__currentLoopData = $errors->all(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $error): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <li><?php echo e($error); ?></li>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        </ul>
        <button type="button" class="close" data-dismiss="alert">
            <span>&times;</span>
        </button>
    </div>
    <?php endif; ?>

    <!-- Main Form -->
    <form method="POST" action="<?php echo e(route('sp-sipt.update', $spSipt->id)); ?>" enctype="multipart/form-data" id="formSpSipt">
        <?php echo csrf_field(); ?>

        <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="<?php echo e($spSipt->nomor_surat ?? '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 <?php $__errorArgs = ['pemohon_nama'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                               name="pemohon_nama"
                               value="<?php echo e(old('pemohon_nama', $spSipt->pemohon_nama)); ?>"
                               placeholder="Masukkan nama lengkap"
                               required>
                        <?php $__errorArgs = ['pemohon_nama'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>

                    <div class="form-group col-md-6">
                        <label>Tempat/Tanggal Lahir</label>
                        <div class="input-group">
                            <input type="text"
                                   class="form-control <?php $__errorArgs = ['pemohon_tempat_lahir'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                   name="pemohon_tempat_lahir"
                                   value="<?php echo e(old('pemohon_tempat_lahir', $spSipt->pemohon_tempat_lahir)); ?>"
                                   placeholder="Tempat lahir">
                            <input type="date"
                                   class="form-control <?php $__errorArgs = ['pemohon_tanggal_lahir'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                   name="pemohon_tanggal_lahir"
                                   value="<?php echo e(old('pemohon_tanggal_lahir', Carbon\Carbon::parse($spSipt->pemohon_tanggal_lahir)->format('Y-m-d'))); ?>">
                        </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 <?php $__errorArgs = ['pemohon_nik'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                               name="pemohon_nik"
                               value="<?php echo e(old('pemohon_nik', $spSipt->pemohon_nik)); ?>"
                               placeholder="16 digit NIK"
                               maxlength="16"
                               pattern="[0-9]{16}"
                               required>
                        <?php $__errorArgs = ['pemohon_nik'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>

                    <div class="form-group col-md-6">
                        <label>Pekerjaan</label>
                        <input type="text"
                               class="form-control <?php $__errorArgs = ['pemohon_pekerjaan'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                               name="pemohon_pekerjaan"
                               value="<?php echo e(old('pemohon_pekerjaan', $spSipt->pemohon_pekerjaan)); ?>"
                               placeholder="Masukkan pekerjaan">
                    </div>
                </div>

                <div class="form-group">
                    <label>Alamat <span class="required">*</span></label>
                    <textarea class="form-control <?php $__errorArgs = ['pemohon_alamat'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                              name="pemohon_alamat"
                              rows="2"
                              placeholder="Masukkan alamat lengkap"
                              required><?php echo e(old('pemohon_alamat', $spSipt->pemohon_alamat)); ?></textarea>
                    <?php $__errorArgs = ['pemohon_alamat'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                        <div class="invalid-feedback"><?php echo e($message); ?></div>
                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                </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 <?php $__errorArgs = ['terlapor_nama'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                               name="terlapor_nama"
                               value="<?php echo e(old('terlapor_nama', $spSipt->terlapor_nama)); ?>"
                               placeholder="Masukkan nama lengkap"
                               required>
                        <?php $__errorArgs = ['terlapor_nama'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>

                    <div class="form-group col-md-6">
                        <label>Tempat/Tanggal Lahir</label>
                        <div class="input-group">
                            <input type="text"
                                   class="form-control <?php $__errorArgs = ['terlapor_tempat_lahir'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                   name="terlapor_tempat_lahir"
                                   value="<?php echo e(old('terlapor_tempat_lahir', $spSipt->terlapor_tempat_lahir)); ?>"
                                   placeholder="Tempat lahir">
                            <input type="date"
                                   class="form-control <?php $__errorArgs = ['terlapor_tanggal_lahir'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                   name="terlapor_tanggal_lahir"
                                   value="<?php echo e(old('terlapor_tanggal_lahir', Carbon\Carbon::parse($spSipt->terlapor_tanggal_lahir)->format('Y-m-d'))); ?>">
                        </div>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label>Nomor KTP</label>
                        <input type="text"
                               class="form-control <?php $__errorArgs = ['terlapor_nik'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                               name="terlapor_nik"
                               value="<?php echo e(old('terlapor_nik', $spSipt->terlapor_nik)); ?>"
                               placeholder="16 digit NIK"
                               maxlength="16"
                               pattern="[0-9]{16}">
                        <?php $__errorArgs = ['terlapor_nik'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>

                    <div class="form-group col-md-6">
                        <label>Pekerjaan</label>
                        <input type="text"
                               class="form-control <?php $__errorArgs = ['terlapor_pekerjaan'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                               name="terlapor_pekerjaan"
                               value="<?php echo e(old('terlapor_pekerjaan', $spSipt->terlapor_pekerjaan)); ?>"
                               placeholder="Masukkan pekerjaan">
                    </div>
                </div>

                <div class="form-group">
                    <label>Alamat</label>
                    <textarea class="form-control <?php $__errorArgs = ['terlapor_alamat'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                              name="terlapor_alamat"
                              rows="2"
                              placeholder="Masukkan alamat lengkap"><?php echo e(old('terlapor_alamat', $spSipt->terlapor_alamat)); ?></textarea>
                    <?php $__errorArgs = ['terlapor_alamat'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                        <div class="invalid-feedback"><?php echo e($message); ?></div>
                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                </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 <?php $__errorArgs = ['ketua_rt'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                               name="ketua_rt"
                               value="<?php echo e(old('ketua_rt', $spSipt->ketua_rt)); ?>"
                               placeholder="">
                        <?php $__errorArgs = ['ketua_rt'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                    <div class="form-group col-md-4">
                        <label>Nama RT</label>
                        <input type="text"
                               class="form-control <?php $__errorArgs = ['nama_rt'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                               name="nama_rt"
                               value="<?php echo e(old('nama_rt', $spSipt->nama_rt)); ?>"
                               placeholder="">
                        <?php $__errorArgs = ['nama_rt'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                    <div class="form-group col-md-4">
                        <label>Lokasi Tanah RT</label>
                        <input type="text"
                               class="form-control <?php $__errorArgs = ['lokasi_tanah_rt'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                               name="lokasi_tanah_rt"
                               value="<?php echo e(old('lokasi_tanah_rt', $spSipt->lokasi_tanah_rt)); ?>"
                               placeholder="">
                        <?php $__errorArgs = ['lokasi_tanah_rt'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group col-md-4">
                        <label for="Kampung">Kampung/Kelurahan</label>
                        <select class="form-control select2 <?php $__errorArgs = ['kampung'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" id="kampung" name="kampung" required>
                            <option value="">-- Pilih Kampung --</option>
                            <?php $__currentLoopData = $kampungs; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $kampung): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($kampung->id); ?>"
                                    <?php echo e(old('kampung', $spSipt->kampung) == $kampung->id ? 'selected' : ''); ?>>
                                    <?php echo e($kampung->nama_kampung); ?>

                                </option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                        <?php $__errorArgs = ['kampung'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <small class="text-danger"><?php echo e($message); ?></small>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                    <div class="form-group col-md-4">
                        <label for="Kecamatan">Kecamatan</label>
                        <select class="form-control select2 <?php $__errorArgs = ['kecamatan_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" id="kecamatan_id" name="kecamatan_id" required>
                            <option value="">-- Pilih Kecamatan --</option>
                            <?php $__currentLoopData = $kecamatans; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $kecamatan): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($kecamatan->id); ?>"
                                    <?php echo e(old('kecamatan_id', $spSipt->kecamatan_id) == $kecamatan->id ? 'selected' : ''); ?>>
                                    <?php echo e($kecamatan->nama_kecamatan); ?>

                                </option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                        <?php $__errorArgs = ['kecamatan_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <small class="text-danger"><?php echo e($message); ?></small>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                    <div class="form-group col-md-4">
                        <label>Kota/Kabupaten</label>
                        <input type="text"
                               class="form-control <?php $__errorArgs = ['lokasi_kota'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                               name="lokasi_kota"
                               value="<?php echo e(old('lokasi_kota', $spSipt->lokasi_kota)); ?>"
                               placeholder="Nama kota">
                        <?php $__errorArgs = ['lokasi_kota'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </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 <?php $__errorArgs = ['batas_utara'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                               name="batas_utara"
                               value="<?php echo e(old('batas_utara', $spSipt->batas_utara)); ?>"
                               placeholder="Berbatasan dengan...">
                        <?php $__errorArgs = ['batas_utara'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>

                    <div class="form-group col-md-6">
                        <label>Timur</label>
                        <input type="text"
                               class="form-control <?php $__errorArgs = ['batas_timur'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                               name="batas_timur"
                               value="<?php echo e(old('batas_timur', $spSipt->batas_timur)); ?>"
                               placeholder="Berbatasan dengan...">
                        <?php $__errorArgs = ['batas_timur'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label>Selatan</label>
                        <input type="text"
                               class="form-control <?php $__errorArgs = ['batas_selatan'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                               name="batas_selatan"
                               value="<?php echo e(old('batas_selatan', $spSipt->batas_selatan)); ?>"
                               placeholder="Berbatasan dengan...">
                        <?php $__errorArgs = ['batas_selatan'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>

                    <div class="form-group col-md-6">
                        <label>Barat</label>
                        <input type="text"
                               class="form-control <?php $__errorArgs = ['batas_barat'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                               name="batas_barat"
                               value="<?php echo e(old('batas_barat', $spSipt->batas_barat)); ?>"
                               placeholder="Berbatasan dengan...">
                        <?php $__errorArgs = ['batas_barat'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                </div>

                <!-- PERNYATAAN -->
                <h6 class="section-title mt-4">PERNYATAAN</h6>

                <div class="form-group">
                    <div class="form-group col-md-4">
                        <label>Bukti (Kwitansi) Pembelian Tanggal</label>
                        <input type="date"
                               class="form-control <?php $__errorArgs = ['tanggal_sertifikat'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                               name="tanggal_sertifikat"
                               value="<?php echo e(old('tanggal_sertifikat', Carbon\Carbon::parse($spSipt->tanggal_sertifikat)->format('Y-m-d'))); ?>"
                               placeholder="">
                        <?php $__errorArgs = ['tanggal_sertifikat'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </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 <?php $__errorArgs = ['nomor_tanggal_surat_penguasaan_tanah'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" cols="30" rows="3">
                            <?php echo e(old('nomor_tanggal_surat_penguasaan_tanah', $spSipt->nomor_tanggal_surat_penguasaan_tanah)); ?>

                        </textarea>
                        <?php $__errorArgs = ['nomor_tanggal_surat_penguasaan_tanah'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                </div>

               <!-- UPLOAD DOKUMEN -->
                <h6 class="section-title mt-4">UPLOAD DOKUMEN</h6>

                <!-- Dokumen yang Sudah Ada -->
                <?php if($spSipt->dokumen && $spSipt->dokumen->count() > 0): ?>
                <div class="card mb-3">
                    <div class="card-header bg-light">
                        <h6 class="mb-0"><i class="fas fa-folder-open mr-2"></i>Dokumen yang Sudah Diupload</h6>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-sm table-hover">
                                <thead class="bg-light">
                                    <tr>
                                        <th width="5%">No</th>
                                        <th width="20%">Jenis Dokumen</th>
                                        <th width="30%">Nama File</th>
                                        <th width="10%">Ukuran</th>
                                        <th width="15%">Tanggal Upload</th>
                                        <th width="20%" class="text-center">Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php $__currentLoopData = $spSipt->dokumen; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $dok): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <tr>
                                        <td><?php echo e($index + 1); ?></td>
                                        <td>
                                            <span class="badge badge-<?php echo e($dok->jenis_dokumen == 'kwitansi' ? 'primary' : 'info'); ?>">
                                                <?php echo e(ucfirst(str_replace('_', ' ', $dok->jenis_dokumen))); ?>

                                            </span>
                                        </td>
                                        <td>
                                            <i class="fas fa-<?php echo e(in_array($dok->mime_type, ['image/png', 'image/jpeg', 'image/jpg']) ? 'image' : 'file-pdf'); ?> mr-1"></i>
                                            <small><?php echo e($dok->nama_file); ?></small>
                                        </td>
                                        <td>
                                            <?php if($dok->ukuran_file): ?>
                                                <small><?php echo e(number_format($dok->ukuran_file / 1024, 2)); ?> KB</small>
                                            <?php else: ?>
                                                <small class="text-muted">-</small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <small class="text-muted">
                                                <?php echo e(\Carbon\Carbon::parse($dok->created_at)->format('d/m/Y H:i')); ?>

                                            </small>
                                        </td>
                                        <td class="text-center">
                                            <div class="btn-group btn-group-sm">
                                                <!-- Tombol Lihat -->
                                                <a href="<?php echo e(Storage::url($dok->path_file)); ?>"
                                                target="_blank"
                                                class="btn btn-primary btn-sm"
                                                title="Lihat File">
                                                    <i class="fas fa-eye"></i>
                                                </a>

                                                <!-- Tombol Download -->
                                                <a href="<?php echo e(Storage::url($dok->path_file)); ?>"
                                                download="<?php echo e($dok->nama_file); ?>"
                                                class="btn btn-success btn-sm"
                                                title="Download File">
                                                    <i class="fas fa-download"></i>
                                                </a>

                                                <!-- Tombol Hapus -->
                                                <button type="button"
                                                        class="btn btn-danger btn-sm"
                                                        onclick="confirmDeleteDocument(<?php echo e($dok->id); ?>, '<?php echo e($dok->nama_file); ?>')"
                                                        title="Hapus File">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>

                                    <!-- Preview untuk Image -->
                                    <?php if(in_array($dok->mime_type, ['image/png', 'image/jpeg', 'image/jpg', 'image/gif'])): ?>
                                    <tr class="bg-light">
                                        <td colspan="6" class="text-center py-3">
                                            <img src="<?php echo e(Storage::url($dok->path_file)); ?>"
                                                alt="Preview <?php echo e($dok->nama_file); ?>"
                                                class="img-thumbnail"
                                                style="max-height: 200px; max-width: 100%; object-fit: contain; cursor: pointer;"
                                                onclick="window.open('<?php echo e(Storage::url($dok->path_file)); ?>', '_blank')">
                                            <br>
                                            <small class="text-muted">Klik gambar untuk melihat ukuran penuh</small>
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <?php else: ?>
                <div class="alert alert-warning mb-3">
                    <i class="fas fa-info-circle mr-2"></i>
                    Belum ada dokumen yang diupload
                </div>
                <?php endif; ?>

                <!-- Form Upload Dokumen Baru -->
                <div class="card">
                    <div class="card-header bg-success text-white">
                        <h6 class="mb-0"><i class="fas fa-cloud-upload-alt mr-2"></i>Upload Dokumen Baru</h6>
                    </div>
                    <div class="card-body">
                        <div class="form-row">
                            <!-- Upload KWITANSI -->
                            <div class="form-group col-md-6">
                                <label class="font-weight-bold">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 font-weight-bold">Klik untuk upload file kwitansi</p>
                                    <small class="text-muted d-block mb-2">Format: PDF, JPG, JPEG, PNG</small>
                                    <small class="text-muted">Maksimal: 5MB</small>
                                    <input type="file"
                                        id="ktp_file"
                                        name="kwitansi"
                                        class="d-none"
                                        accept=".pdf,image/*"
                                        onchange="showFileInfo(this, 'ktp_preview')">
                                </div>
                                <div id="ktp_preview" class="mt-2"></div>
                                <?php $__errorArgs = ['kwitansi'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                    <small class="text-danger d-block mt-2">
                                        <i class="fas fa-exclamation-circle mr-1"></i><?php echo e($message); ?>

                                    </small>
                                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                            </div>

                            <!-- Upload Dokumen Pendukung -->
                            <div class="form-group col-md-6">
                                <label class="font-weight-bold">Upload Dokumen Pendukung (PDF/DOC)</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 font-weight-bold">Klik untuk upload dokumen pendukung</p>
                                    <small class="text-muted d-block mb-2">Format: PDF, DOC, DOCX</small>
                                    <small class="text-muted">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>
                                <div id="template_preview" class="mt-2"></div>
                                <?php $__errorArgs = ['dokumen_template'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                    <small class="text-danger d-block mt-2">
                                        <i class="fas fa-exclamation-circle mr-1"></i><?php echo e($message); ?>

                                    </small>
                                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                            </div>
                        </div>
                    </div>
                </div>


                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label>Peruntukan Bidang Tanah</label>
                        <input type="text"
                               class="form-control <?php $__errorArgs = ['peruntukan_bidang_tanah'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                               name="peruntukan_bidang_tanah"
                               value="<?php echo e(old('peruntukan_bidang_tanah', $spSipt->peruntukan_bidang_tanah)); ?>"
                               placeholder="">
                        <?php $__errorArgs = ['peruntukan_bidang_tanah'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>

                    <div class="form-group col-md-6">
                        <label>Uang Ganti Kerugian/Santunan</label>
                        <input type="text"
                               class="form-control <?php $__errorArgs = ['uang_ganti_kerugian'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                               name="uang_ganti_kerugian"
                               value="<?php echo e(old('uang_ganti_kerugian', $spSipt->uang_ganti_kerugian)); ?>"
                               placeholder="">
                        <?php $__errorArgs = ['uang_ganti_kerugian'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </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 UTM (Zone 50S)</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%">Easting (m)</th>
                                            <th width="35%">Northing (m)</th>
                                            <th width="20%" class="text-center">Aksi</th>
                                        </tr>
                                    </thead>
                                    <tbody id="coordinatesList">
                                        <?php $__currentLoopData = $spSipt->coordinates_array; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $coord): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <?php
                                                // Convert Lat/Lng to UTM if not already available
                                                $easting = $coord['easting'] ?? null;
                                                $northing = $coord['northing'] ?? null;
                                            ?>
                                            <tr id="coord-<?php echo e($index + 1); ?>">
                                                <td class="align-middle font-weight-bold"><?php echo e($index + 1); ?></td>
                                                <td>
                                                    <input type="text" class="form-control form-control-sm"
                                                           name="easting[<?php echo e($index + 1); ?>]" id="easting_<?php echo e($index + 1); ?>"
                                                           value="<?php echo e($easting); ?>"
                                                           placeholder="500000"
                                                           onchange="updateMapAndCalculate()">
                                                </td>
                                                <td>
                                                    <input type="text" class="form-control form-control-sm"
                                                           name="northing[<?php echo e($index + 1); ?>]" id="northing_<?php echo e($index + 1); ?>"
                                                           value="<?php echo e($northing); ?>"
                                                           placeholder="9862000"
                                                           onchange="updateMapAndCalculate()">
                                                </td>
                                                <td class="text-center">
                                                    <button type="button" class="btn btn-danger btn-sm"
                                                            onclick="removeCoordinate(<?php echo e($index + 1); ?>)" title="Hapus">
                                                        <i class="fas fa-times"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </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 inputs for coordinate data -->
                                <input type="hidden" name="coordinates_data" id="coordinates_data" value="<?php echo e(old('coordinates_data', $spSipt->coordinates_data)); ?>">
                                <input type="hidden" name="map_image_data" id="map_image_data" value="<?php echo e(old('map_image_data', $spSipt->map_image_data)); ?>">
                                <input type="hidden" name="luas_terukur" id="luas_terukur" value="<?php echo e(old('luas_terukur', $spSipt->luas_terukur)); ?>">
                                <!-- Hidden inputs for lat/lng conversions -->
                                <div id="latLngHiddenInputs"></div>
                            </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"><?php echo e(count($spSipt->coordinates_array)); ?></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(true)">
                                        <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='<?php echo e(route('sp-sipt.index')); ?>'" title="Kembali">
                <i class="fas fa-arrow-left"></i>
            </button>
        </div>
    </form>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('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>
<!-- SweetAlert2 JS -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!-- html2canvas for map capture -->
<script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
<script>
// ============================================
// UTM COORDINATE CONVERSION SETUP
// ============================================

// Define UTM Zone 50N (for Kalimantan Timur - Berau area)
// EPSG:32650 = WGS 84 / UTM zone 50N
proj4.defs("EPSG:32650", "+proj=utm +zone=50 +datum=WGS84 +units=m +no_defs");

// Helper function to convert UTM to Lat/Lng (EXACT copy from create.blade.php)
function utmToLatLng(easting, northing) {
    // Relaxed validation: accept any positive easting/northing
    easting = parseFloat(easting);
    northing = parseFloat(northing);
    if (isNaN(easting) || isNaN(northing) || easting <= 0 || northing <= 0) {
        console.error(`Invalid UTM coordinate: Easting ${easting}, Northing ${northing}`);
        return null;
    }
    try {
        // Use EPSG:32650 definition for Zone 50N
        const [lng, lat] = proj4('EPSG:32650', '+proj=longlat +datum=WGS84 +no_defs', [easting, northing]);
        console.log(`UTM (${easting}, ${northing}) → Lat/Lng (${lat}, ${lng})`);
        return { lat: lat, lng: lng };
    } catch (error) {
        console.error('Error converting UTM to Lat/Lng:', error);
        return null;
    }
}

// Helper function to convert Lat/Lng to UTM (Zone 50N ONLY)
function latLngToUTM(lat, lng) {
    try {
        const [easting, northing] = proj4('+proj=longlat +datum=WGS84 +no_defs', 'EPSG:32650', [lng, lat]);
        return { easting: easting, northing: northing };
    } catch (error) {
        console.error('Error converting Lat/Lng to UTM:', error);
        return null;
    }
}

// ============================================
// GLOBAL VARIABLES
// ============================================

// Global variables
let map;
let polygon = null;
let markers = [];
let coordinateCount = <?php echo e(count($spSipt->coordinates_array)); ?>;
let coordinates = <?php echo json_encode($spSipt->coordinates_array, 15, 512) ?>; // Store as {lat, lng} for map
let coordinatesUTM = []; // Store as {easting, northing} for display
// Konfirmasi hapus dokumen dengan SweetAlert2
// Konfirmasi hapus dokumen dengan SweetAlert2
function confirmDeleteDocument(dokumenId, namaFile) {
    Swal.fire({
        title: 'Hapus Dokumen?',
        html: `<p>File: <strong>${namaFile}</strong></p><p class="text-danger">File yang dihapus tidak dapat dikembalikan!</p>`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#dc3545',
        cancelButtonColor: '#6c757d',
        confirmButtonText: '<i class="fas fa-trash mr-1"></i> Ya, Hapus!',
        cancelButtonText: '<i class="fas fa-times mr-1"></i> Batal',
        reverseButtons: true,
        focusCancel: true
    }).then((result) => {
        if (result.isConfirmed) {
            // Show loading
            Swal.fire({
                title: 'Menghapus...',
                html: 'Sedang menghapus dokumen',
                allowOutsideClick: false,
                allowEscapeKey: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });

            // Get CSRF token
            const token = $('meta[name="csrf-token"]').attr('content');

            // Generate URL using Laravel route helper
            const deleteUrl = "<?php echo e(route('sp-sipt.dokumen.delete', ':id')); ?>".replace(':id', dokumenId);

            // Send AJAX request
            $.ajax({
                url: deleteUrl,
                type: 'DELETE',
                data: {
                    _token: token
                },
                success: function(response) {
                    Swal.fire({
                        title: 'Berhasil!',
                        text: 'Dokumen berhasil dihapus',
                        icon: 'success',
                        confirmButtonColor: '#28a745',
                        confirmButtonText: 'OK'
                    }).then(() => {
                        location.reload();
                    });
                },
                error: function(xhr) {
                    let errorMsg = 'Gagal menghapus dokumen';
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMsg = xhr.responseJSON.message;
                    }

                    Swal.fire({
                        title: 'Gagal!',
                        text: errorMsg,
                        icon: 'error',
                        confirmButtonColor: '#dc3545',
                        confirmButtonText: 'OK'
                    });
                }
            });
        }
    });
}
// 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);

            // Convert to UTM for display
            const utmCoord = latLngToUTM(lat, lng);

            if (!utmCoord) {
                alert('Gagal mengkonversi koordinat ke UTM');
                return;
            }

            if (confirm(`Tambah koordinat?\nEasting: ${utmCoord.easting.toFixed(2)} m\nNorthing: ${utmCoord.northing.toFixed(2)} m`)) {
                addCoordinateWithValues(lat, lng);
            }
        });

        // Invalidate size to ensure map renders correctly
        setTimeout(() => {
            map.invalidateSize();
            updateMapAndCalculate();
        }, 100);
    } catch (error) {
        console.error('Error initializing map:', error);
        alert('Gagal memuat peta. Silakan coba lagi.');
    }
}

// Update map and calculate area (renamed from updateMapPolygon for consistency)
function updateMapAndCalculate() {
    try {
        // Clear existing
        if (polygon) {
            map.removeLayer(polygon);
        }
        markers.forEach(marker => map.removeLayer(marker));
        markers = [];

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

        rows.forEach((row, index) => {
            const coordId = row.id.split('-')[1];
            const eastingInput = document.getElementById(`easting_${coordId}`);
            const northingInput = document.getElementById(`northing_${coordId}`);

            if (!eastingInput || !northingInput) return;

            const easting = parseFloat(eastingInput.value);
            const northing = parseFloat(northingInput.value);

            if (!isNaN(easting) && !isNaN(northing)) {
                // Store UTM coordinates
                coordinatesUTM.push({easting: easting, northing: northing});

                // Convert UTM to Lat/Lng for map display
                const latLng = utmToLatLng(easting, northing);

                if (latLng && !isNaN(latLng.lat) && !isNaN(latLng.lng)) {
                    coordinates.push({lat: latLng.lat, lng: latLng.lng});

                    // Add numbered marker
                    const marker = L.marker([latLng.lat, latLng.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 whenever valid polygon exists (delay to let map render)
            setTimeout(() => {
                captureMap();
            }, 500);
        } else {
            // Reset area if insufficient coordinates
            document.getElementById('calculatedArea').textContent = '0 m²';
            // Clear map_image_data if polygon is invalid
            document.getElementById('map_image_data').value = '';
        }

        // Update hidden inputs with both UTM and Lat/Lng
        updateHiddenInputs();
    } catch (error) {
        console.error('Error updating polygon:', error);
    }
}

// Update hidden inputs with coordinate data
function updateHiddenInputs() {
    try {
        // Update coordinates_data with lat/lng for backward compatibility
        document.getElementById('coordinates_data').value = JSON.stringify(coordinates);

        // Create/update hidden inputs for lat/lng (for database storage)
        const hiddenContainer = document.getElementById('latLngHiddenInputs');
        hiddenContainer.innerHTML = '';

        coordinates.forEach((coord, index) => {
            // Add lat hidden input
            const latInput = document.createElement('input');
            latInput.type = 'hidden';
            latInput.name = `lat[${index + 1}]`;
            latInput.value = coord.lat;
            hiddenContainer.appendChild(latInput);

            // Add lng hidden input
            const lngInput = document.createElement('input');
            lngInput.type = 'hidden';
            lngInput.name = `lng[${index + 1}]`;
            lngInput.value = coord.lng;
            hiddenContainer.appendChild(lngInput);
        });
    } catch (error) {
        console.error('Error updating hidden inputs:', 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="easting[${coordinateCount}]" id="easting_${coordinateCount}"
                   placeholder="500000"
                   onchange="updateMapAndCalculate()">
        </td>
        <td>
            <input type="text" class="form-control form-control-sm"
                   name="northing[${coordinateCount}]" id="northing_${coordinateCount}"
                   placeholder="9862000"
                   onchange="updateMapAndCalculate()">
        </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 (from map click)
function addCoordinateWithValues(lat, lng) {
    coordinateCount++;
    const tbody = document.getElementById('coordinatesList');
    const rowNumber = tbody.children.length + 1;

    // Convert Lat/Lng to UTM for display
    const utmCoord = latLngToUTM(lat, lng);

    if (!utmCoord) {
        alert('Gagal mengkonversi koordinat ke UTM');
        return;
    }

    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="easting[${coordinateCount}]" id="easting_${coordinateCount}"
                   value="${utmCoord.easting.toFixed(2)}"
                   onchange="updateMapAndCalculate()">
        </td>
        <td>
            <input type="text" class="form-control form-control-sm"
                   name="northing[${coordinateCount}]" id="northing_${coordinateCount}"
                   value="${utmCoord.northing.toFixed(2)}"
                   onchange="updateMapAndCalculate()">
        </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
    updateMapAndCalculate();
}

// 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;
            });

            updateMapAndCalculate();
        }
    }
}

// Calculate polygon area using UTM coordinates (MORE ACCURATE)
function calculateArea() {
    if (coordinatesUTM.length < 3) {
        document.getElementById('calculatedArea').textContent = '0 m²';
        document.getElementById('luas_terukur').value = '0';
        return;
    }

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

        // Shoelace formula using UTM coordinates (in meters)
        for (let i = 0; i < n; i++) {
            const j = (i + 1) % n;
            area += coordinatesUTM[i].easting * coordinatesUTM[j].northing;
            area -= coordinatesUTM[j].easting * coordinatesUTM[i].northing;
        }

        area = Math.abs(area / 2);

        console.log('Calculated area (UTM-based):', area.toFixed(2), 'm²');

        // Update display
        document.getElementById('calculatedArea').textContent =
            area.toLocaleString('id-ID', {maximumFractionDigits: 2}) + ' m²';

        // Save to hidden input for backend
        document.getElementById('luas_terukur').value = area.toFixed(2);
    } catch (error) {
        console.error('Error calculating area:', error);
        document.getElementById('calculatedArea').textContent = 'Error';
        document.getElementById('luas_terukur').value = '0';
    }
}

// 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 polygon only as image
function captureMap(showAlert = false) {
    try {
        if (coordinates.length < 3) {
            if (showAlert) {
                alert('Minimal 3 koordinat diperlukan untuk capture peta');
            }
            return false;
        }

        // Show loading indicator
        if (showAlert) {
            Swal.fire({
                title: 'Sedang capture peta...',
                text: 'Mohon tunggu sebentar',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
        }

        // Get polygon bounds
        const bounds = polygon.getBounds();
        const sw = bounds.getSouthWest(); // Southwest corner
        const ne = bounds.getNorthEast(); // Northeast corner

        // Add padding (8% on each side) - lebih kecil untuk zoom lebih dekat
        const latRange = ne.lat - sw.lat;
        const lngRange = ne.lng - sw.lng;
        const latPadding = latRange * 0.08;
        const lngPadding = lngRange * 0.08;

        const minLat = sw.lat - latPadding;
        const maxLat = ne.lat + latPadding;
        const minLng = sw.lng - lngPadding;
        const maxLng = ne.lng + lngPadding;

        // Calculate aspect ratio to maintain polygon shape
        const totalLatRange = maxLat - minLat;
        const totalLngRange = maxLng - minLng;
        const aspectRatio = totalLngRange / totalLatRange;

        // Create canvas with dynamic size based on polygon shape - diperbesar ke 1200px
        const canvas = document.createElement('canvas');
        let canvasWidth, canvasHeight;
        const maxDimension = 1200; // Diperbesar dari 800 ke 1200 untuk polygon lebih besar

        // Set max dimension, adjust other dimension to maintain aspect ratio
        if (aspectRatio > 1) {
            // Landscape (wider than tall)
            canvasWidth = maxDimension;
            canvasHeight = Math.round(maxDimension / aspectRatio);
        } else {
            // Portrait (taller than wide)
            canvasHeight = maxDimension;
            canvasWidth = Math.round(maxDimension * aspectRatio);
        }

        canvas.width = canvasWidth;
        canvas.height = canvasHeight;
        const ctx = canvas.getContext('2d');

        // White background
        ctx.fillStyle = '#ffffff';
        ctx.fillRect(0, 0, canvasWidth, canvasHeight);

        // Convert lat/lng to canvas coordinates (using proper map projection)
        function latLngToCanvas(lat, lng) {
            const x = ((lng - minLng) / (maxLng - minLng)) * canvasWidth;
            const y = ((maxLat - lat) / (maxLat - minLat)) * canvasHeight;
            return { x, y };
        }

        // Get polygon latlngs from Leaflet (this ensures exact same coordinates as displayed)
        const polygonLatLngs = polygon.getLatLngs()[0];

        // Draw polygon
        ctx.beginPath();
        polygonLatLngs.forEach((latlng, index) => {
            const point = latLngToCanvas(latlng.lat, latlng.lng);
            if (index === 0) {
                ctx.moveTo(point.x, point.y);
            } else {
                ctx.lineTo(point.x, point.y);
            }
        });
        ctx.closePath();

        // Fill polygon with same color as Leaflet (yellow with opacity)
        ctx.fillStyle = 'rgba(255, 255, 0, 0.3)'; // #ffff00 with 0.3 opacity
        ctx.fill();

        // Stroke polygon with same color as Leaflet (red)
        ctx.strokeStyle = '#ff0000';
        ctx.lineWidth = 4; // Diperbesar dari 3 ke 4
        ctx.stroke();

        // Draw coordinate points and labels - diperbesar dan lebih jelas
        polygonLatLngs.forEach((latlng, index) => {
            const point = latLngToCanvas(latlng.lat, latlng.lng);

            // Draw point circle - diperbesar
            ctx.beginPath();
            ctx.arc(point.x, point.y, 10, 0, 2 * Math.PI); // Diperbesar dari 6 ke 10
            ctx.fillStyle = '#ff0000';
            ctx.fill();
            ctx.strokeStyle = '#ffffff';
            ctx.lineWidth = 3; // Diperbesar dari 2 ke 3
            ctx.stroke();

            // Draw point label with background - diperbesar
            const label = (index + 1).toString();
            ctx.font = 'bold 20px Arial'; // Diperbesar dari 14px ke 20px
            const textMetrics = ctx.measureText(label);
            const textWidth = textMetrics.width;
            const textHeight = 24; // Disesuaikan dengan font size

            // Background for label - lebih besar dan lebih jelas
            ctx.fillStyle = 'rgba(255, 255, 255, 0.95)'; // Lebih opaque
            ctx.fillRect(point.x + 14, point.y - textHeight, textWidth + 12, textHeight + 6);

            // Border untuk background label
            ctx.strokeStyle = '#000000';
            ctx.lineWidth = 1;
            ctx.strokeRect(point.x + 14, point.y - textHeight, textWidth + 12, textHeight + 6);

            // Label text
            ctx.fillStyle = '#000000';
            ctx.fillText(label, point.x + 20, point.y - 6);
        });

        // Convert canvas to base64 image
        const imageData = canvas.toDataURL('image/png', 0.95);

        // Store in hidden input
        document.getElementById('map_image_data').value = imageData;

        console.log('Polygon captured successfully, image data length:', imageData.length);

        if (showAlert) {
            Swal.fire({
                icon: 'success',
                title: 'Berhasil!',
                text: 'Polygon berhasil di-capture',
                timer: 2000,
                showConfirmButton: false
            });
        }

        return true;

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

        if (showAlert) {
            Swal.fire({
                icon: 'error',
                title: 'Gagal!',
                text: 'Gagal capture polygon. Silakan coba lagi.',
            });
        }

        return false;
    }
}

// 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 = [];

            console.log('=== FORM SUBMIT DEBUG ===');
            console.log('Coordinates count:', coordinates.length);
            console.log('CoordinatesUTM count:', coordinatesUTM.length);
            console.log('Coordinates data size:', JSON.stringify(coordinates).length, 'bytes');
            console.log('Form action:', $(this).attr('action'));
            console.log('Form method:', $(this).attr('method'));

            // 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': '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;
            }

            // Check map_image_data
            const mapImageData = $('#map_image_data').val();
            console.log('Map image data size:', mapImageData ? mapImageData.length : 0, 'bytes');

            if (!mapImageData || mapImageData.trim() === '') {
                errors.push('Data gambar peta belum ter-capture. Silakan tunggu sebentar atau klik tombol Capture manual.');
                isValid = false;

                // Try to auto-capture one more time
                if (coordinates.length >= 3) {
                    captureMap();
                }
            }

            if (!isValid) {
                e.preventDefault();
                console.error('Form validation failed:', errors);

                // 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);
                }
            } else {
                console.log('✓ Form validation passed, submitting...');

                // Show loading indicator
                const submitBtn = $(this).find('button[type="submit"]');
                submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Menyimpan...');
            }
        });

        // 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 {
        // Convert existing coordinates to UTM for display
        convertExistingCoordinatesToUTM();

        initMap();
        initializeValidation();
        $('[data-toggle="tooltip"]').tooltip();
    } catch (error) {
        console.error('Error during initialization:', error);
        alert('Terjadi kesalahan saat memuat halaman. Silakan coba lagi.');
    }
});

// Convert existing Lat/Lng coordinates to UTM for input fields
function convertExistingCoordinatesToUTM() {
    const rows = document.querySelectorAll('#coordinatesList tr');

    rows.forEach((row, index) => {
        const coordId = row.id.split('-')[1];
        const eastingInput = document.getElementById(`easting_${coordId}`);
        const northingInput = document.getElementById(`northing_${coordId}`);

        if (eastingInput && northingInput && coordinates[index]) {
            // If UTM values are not set, convert from lat/lng
            if (!eastingInput.value || !northingInput.value) {
                const coord = coordinates[index];
                const utmCoord = latLngToUTM(coord.lat, coord.lng);

                if (utmCoord) {
                    eastingInput.value = utmCoord.easting.toFixed(2);
                    northingInput.value = utmCoord.northing.toFixed(2);
                }
            }
        }
    });
}
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('admin-layouts.master', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH C:\laragon\www\webgis-biduk\resources\views/admin/sp-sipt/edit.blade.php ENDPATH**/ ?>