@extends('admin-layouts.master')

@section('title', 'Peta Lokasi - Sistem Informasi Geografis Tanah')

@push('styles')
<!-- Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<style>
    /* Enhanced Table Styles */
.table-row-clickable {
    transition: all 0.3s ease;
}

.table-row-clickable:hover {
    background-color: #f8f9fa !important;
    transform: translateX(2px);
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.table-row-clickable.table-primary {
    background-color: #cfe2ff !important;
    font-weight: 500;
}

/* Custom scrollbar for table container */
#tableContainer::-webkit-scrollbar {
    width: 8px;
}

#tableContainer::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

#tableContainer::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 4px;
}

#tableContainer::-webkit-scrollbar-thumb:hover {
    background: #555;
}

/* Table header sticky positioning */
.table thead th {
    position: sticky;
    top: 0;
    background-color: #1e40af;
    z-index:
}
</style>
@endpush

@section('content')
<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4 fade-in-up">
    <div>
        <h1 class="h3 mb-0 text-gray-800">Dashboard SKPT</h1>
        <p class="mb-0 text-muted">Monitoring permohonan dan peninjauan tanah</p>
    </div>
    <div>
        {{-- <button class="btn btn-primary btn-sm" onclick="window.print()">
            <i class="fas fa-print mr-1"></i> Print
        </button>
        <button class="btn btn-success btn-sm" onclick="exportData()">
            <i class="fas fa-download mr-1"></i> Export
        </button> --}}
    </div>
</div>

<!-- Statistics Cards -->
<div class="row mb-4">
    <!-- Total Permohonan -->
    <div class="col-xl col-md-6 mb-3">
        <div class="card stats-card primary h-100">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                            Total Permohonan
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                            {{ number_format($stats['total']) }}
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-file-alt fa-2x text-primary opacity-50"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Belum Selesai -->
    <div class="col-xl col-md-6 mb-3">
        <div class="card stats-card warning h-100">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                            Belum Selesai
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                            {{ number_format($stats['belum_selesai']) }}
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-clock fa-2x text-warning opacity-50"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Selesai -->
    <div class="col-xl col-md-6 mb-3">
        <div class="card stats-card success h-100">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                            Selesai
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                            {{ number_format($stats['selesai']) }}
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-check-circle fa-2x text-success opacity-50"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Dokumen Lengkap -->
    <div class="col-xl col-md-6 mb-3">
        <div class="card stats-card info h-100">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                            Dok. Lengkap
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                            {{ number_format($stats['dokumen_lengkap']) }}
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-folder-check fa-2x text-info opacity-50"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Dokumen Belum Lengkap -->
    <div class="col-xl col-md-6 mb-3">
        <div class="card stats-card danger h-100">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-danger text-uppercase mb-1">
                            Dok. Belum
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                            {{ number_format($stats['dokumen_belum_lengkap']) }}
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-folder-xmark fa-2x text-danger opacity-50"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Filter Section -->
<div class="card mb-4">
    <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold text-primary">
            <i class="fas fa-filter mr-2"></i>Filter Data
        </h6>
    </div>
    <div class="card-body">
        <form id="filterForm">
            <div class="row">
                <!-- Search -->
                <div class="col-md-3 mb-3">
                    <label for="searchInput" class="small font-weight-bold">Pencarian</label>
                    <div class="input-group">
                        <div class="input-group-prepend">
                            <span class="input-group-text"><i class="fas fa-search"></i></span>
                        </div>
                        <input type="text" class="form-control" id="searchInput"
                               placeholder="Nama, NIK, No. Registrasi">
                    </div>
                </div>

                <!-- Status -->
                <div class="col-md-3 mb-3">
                    <label for="statusFilter" class="small font-weight-bold">Status</label>
                    <select class="form-control" id="statusFilter">
                        <option value="all">Semua Status</option>
                        <option value="BELUM SELESAI">Belum Selesai</option>
                        <option value="SELESAI">Selesai</option>
                    </select>
                </div>

                <!-- Date From -->
                {{-- <div class="col-md-3 mb-3">
                    <label for="dateFrom" class="small font-weight-bold">Dari Tanggal</label>
                    <input type="date" class="form-control" id="dateFrom">
                </div>

                <!-- Date To -->
                <div class="col-md-3 mb-3">
                    <label for="dateTo" class="small font-weight-bold">Sampai Tanggal</label>
                    <input type="date" class="form-control" id="dateTo">
                </div> --}}
            </div>

            <!-- Action Buttons -->
            <div class="row">
                <div class="col-12">
                    <button type="button" class="btn btn-primary" onclick="applyFilter()">
                        <i class="fas fa-filter mr-1"></i> Terapkan Filter
                    </button>
                    <button type="button" class="btn btn-secondary" onclick="resetFilter()">
                        <i class="fas fa-redo mr-1"></i> Reset
                    </button>
                    <button type="button" class="btn btn-info float-right" onclick="toggleMapView()">
                        <i class="fas fa-map mr-1"></i> <span id="mapToggleText">Sembunyikan Peta</span>
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>
<!-- Map and List Section -->
<div class="row" id="mapSection">
    <!-- Map Column -->
    <div class="col-lg-7 mb-4">
        <div class="card">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-map-marked-alt mr-2"></i>Peta Lokasi SKPT
                </h6>
                <div>
                    <button class="btn btn-sm btn-light" onclick="refreshMap()">
                        <i class="fas fa-sync"></i>
                    </button>
                    <button class="btn btn-sm btn-light" onclick="toggleFullscreen()">
                        <i class="fas fa-expand"></i>
                    </button>
                </div>
            </div>
            <div class="card-body p-0 position-relative">
                <!-- Map Container -->
                <div id="map" style="height: 500px; width: 100%;">
                    <!-- Loading Overlay -->
                    <div id="mapLoading" class="loading-overlay d-none">
                        <div class="text-center">
                            <div class="spinner-border text-primary mb-2" role="status">
                                <span class="sr-only">Loading...</span>
                            </div>
                            <p class="text-muted">Memuat peta...</p>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Map Legend -->
            <div class="card-footer bg-light">
                <div class="row">
                    <div class="col-auto">
                        <span class="badge badge-warning mr-2">●</span> Belum Selesai
                    </div>
                    <div class="col-auto">
                        <span class="badge badge-success mr-2">●</span> Selesai
                    </div>
                    <div class="col text-right">
                        <small class="text-muted">
                            <i class="fas fa-info-circle"></i> Klik polygon untuk detail
                        </small>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Sidebar Column -->
    <div class="col-lg-5 mb-4">
        <!-- Quick Stats Card -->
        {{-- <div class="card mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-chart-pie mr-2"></i>Ringkasan
                </h6>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <div class="small text-muted mb-1">Total Luas Terukur</div>
                    <div class="font-weight-bold" id="totalArea">0 m²</div>
                </div>
                <div class="mb-3">
                    <div class="small text-muted mb-1">Permohonan Hari Ini</div>
                    <div class="font-weight-bold" id="todayCount">0</div>
                </div>
                <div class="mb-3">
                    <div class="small text-muted mb-1">Rata-rata Proses</div>
                    <div class="font-weight-bold">7 hari</div>
                </div>
                <!-- Progress Bar -->
                <div class="mt-4">
                    <div class="small text-muted mb-2">Completion Rate</div>
                    <div class="progress">
                        @php
                            $percentage = $stats['total'] > 0 ? ($stats['selesai'] / $stats['total']) * 100 : 0;
                        @endphp
                        <div class="progress-bar bg-success" role="progressbar"
                             style="width: {{ $percentage }}%"
                             aria-valuenow="{{ $percentage }}" aria-valuemin="0" aria-valuemax="100">
                            {{ number_format($percentage, 1) }}%
                        </div>
                    </div>
                </div>
            </div>
        </div> --}}

        <!-- Recent Applications Card -->
        {{-- <div class="card">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-history mr-2"></i>Terbaru
                </h6>
                <a href="#" class="small">Lihat Semua</a>
            </div>
            <div class="card-body p-0">
                <div class="list-group list-group-flush" style="max-height: 350px; overflow-y: auto;">
                    @foreach($skptApplications->take(5) as $skpt)
                    <div class="list-group-item sidebar-item" onclick="focusOnMap({{ $skpt->id }})">
                        <div class="d-flex w-100 justify-content-between">
                            <div>
                                <h6 class="mb-1">{{ Str::limit($skpt->nama_pemohon, 25) }}</h6>
                                <small class="text-muted">{{ $skpt->no_registrasi }}</small>
                            </div>
                            <small>
                                @if($skpt->status_permohonan == 'SELESAI')
                                    <span class="badge badge-success">Selesai</span>
                                @else
                                    <span class="badge badge-warning">Proses</span>
                                @endif
                            </small>
                        </div>
                        <div class="mt-2">
                            <small class="text-muted">
                                <i class="fas fa-map-marker-alt mr-1"></i>
                                {{ Str::limit($skpt->alamat_tanah ?? 'Alamat tidak tersedia', 30) }}
                            </small>
                        </div>
                        <div class="d-flex justify-content-between mt-2">
                            <small class="text-muted">
                                <i class="fas fa-calendar mr-1"></i>
                                {{ $skpt->created_at->format('d/m/Y') }}
                            </small>
                            <small class="text-muted">
                                <i class="fas fa-ruler mr-1"></i>
                                {{ number_format($skpt->luas, 0) }} m²
                            </small>
                        </div>
                    </div>
                    @endforeach
                </div>
            </div>
        </div> --}}
        {{-- <div class="card">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-history mr-2"></i>Terbaru
                </h6>
                <a href="#" class="small">Lihat Semua</a>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive" style="max-height: 350px; overflow-y: auto;">
                    <table class="table table-striped table-hover">
                        <thead class="thead-dark" style="background-color: #1e40af; color: white; position: sticky; top: 0; z-index: 1;">
                            <tr>
                                <th>NO</th>
                                <th>LOKASI</th>
                                <th>PEMILIK</th>
                                <th>LUAS</th>
                                <th>STATUS</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($skptApplications->take(15) as $index => $skpt)
                            <tr>
                                <td>{{ $index + 1 }}</td>
                                <td>{{ Str::limit($skpt->dataPeninjauan->jalan_gg_blok ?? 'Alamat tidak tersedia', 30) }}, RT {{$skpt->dataPeninjauan->rt ?? ''}} RW {{$skpt->dataPeninjauan->rw ?? ''}}<br>{{$skpt->dataPeninjauan->dataKecamatan->nama_kecamatan ?? ''}}</td>
                                <td>{{ Str::limit($skpt->nama_pemohon, 25) }}</td>
                                <td>{{ number_format($skpt->luas, 0) }} m²</td>
                                <td>
                                    @if($skpt->status_permohonan == 'SELESAI')
                                        <span class="badge badge-success">Selesai</span>
                                    @else
                                        <span class="badge badge-warning">Belum Selesai</span>
                                    @endif
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div> --}}
        <!-- Replace the existing table card with this enhanced version -->
        <div class="card">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-history mr-2"></i>Terbaru
                </h6>
                <div class="d-flex align-items-center">
                    <span class="badge badge-primary mr-3">
                        <span id="loadedCount">0</span> / <span id="totalCount">0</span> Data
                    </span>
                    <button class="btn btn-sm btn-outline-primary" onclick="refreshTableData()">
                        <i class="fas fa-sync"></i>
                    </button>
                </div>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive" id="tableContainer" style="max-height: 500px; overflow-y: auto;">
                    <table class="table table-striped table-hover mb-0">
                        <thead class="thead-dark" style="background-color: #1e40af; color: white; position: sticky; top: 0; z-index: 10;">
                            <tr>
                                <th width="5%">NO</th>
                                <th width="25%">LOKASI</th>
                                <th width="20%">PEMILIK</th>
                                <th width="15%">LUAS</th>
                                <th width="15%">STATUS</th>
                                <th width="20%">TANGGAL</th>
                            </tr>
                        </thead>
                        <tbody id="dataTableBody">
                            <!-- Data will be loaded here -->
                        </tbody>
                    </table>
                    
                    <!-- Loading indicator -->
                    <div id="tableLoading" class="text-center py-3 d-none">
                        <div class="spinner-border spinner-border-sm text-primary" role="status">
                            <span class="sr-only">Loading...</span>
                        </div>
                        <small class="ml-2">Memuat data...</small>
                    </div>
                    
                    <!-- No more data message -->
                    <div id="noMoreData" class="text-center py-3 d-none">
                        <small class="text-muted">Tidak ada data lagi</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- Data Table Section -->
{{-- <div class="card">
    <div class="card-header py-3 d-flex justify-content-between align-items-center">
        <h6 class="m-0 font-weight-bold text-primary">
            <i class="fas fa-table mr-2"></i>Data Permohonan SKPT
        </h6>
        <span class="badge badge-primary badge-pill">
            <span id="dataCount">{{ $skptApplications->count() }}</span> Data
        </span>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover" id="dataTable">
                <thead>
                    <tr>
                        <th width="5%">No</th>
                        <th>No. Registrasi</th>
                        <th>Pemohon</th>
                        <th>NIK</th>
                        <th>Alamat Tanah</th>
                        <th>Luas</th>
                        <th>Status</th>
                        <th>Dokumen</th>
                        <th>Tanggal</th>
                        <th width="10%" class="text-center">Aksi</th>
                    </tr>
                </thead>
                <tbody id="dataTableBody">
                    @php $no = 1; @endphp
                    @foreach($skptApplications as $skpt)
                    <tr>
                        <td>{{ $no++ }}</td>
                        <td>
                            <span class="font-weight-bold">{{ $skpt->no_registrasi }}</span>
                        </td>
                        <td>
                            <div>
                                <span class="font-weight-medium">{{ $skpt->nama_pemohon }}</span><br>
                                <small class="text-muted">{{ $skpt->no_hp ?? '-' }}</small>
                            </div>
                        </td>
                        <td>{{ $skpt->nik }}</td>
                        <td>
                            <small>{{ Str::limit($skpt->alamat_tanah ?? 'Tidak ada alamat', 40) }}</small>
                        </td>
                        <td>
                            <span class="badge badge-light">{{ number_format($skpt->luas, 0) }} m²</span>
                        </td>
                        <td>
                            @if($skpt->status_permohonan == 'SELESAI')
                                <span class="badge badge-success">
                                    <i class="fas fa-check-circle"></i> Selesai
                                </span>
                            @else
                                <span class="badge badge-warning">
                                    <i class="fas fa-clock"></i> Proses
                                </span>
                            @endif
                        </td>
                        <td>
                            @if($skpt->status_kelengkapan_dokumen == 'LENGKAP')
                                <span class="badge badge-info">
                                    <i class="fas fa-folder-check"></i> Lengkap
                                </span>
                            @else
                                <span class="badge badge-danger">
                                    <i class="fas fa-folder-xmark"></i> Belum
                                </span>
                            @endif
                        </td>
                        <td>
                            <small>{{ $skpt->created_at->format('d/m/Y') }}</small>
                        </td>
                        <td class="text-center">
                            <div class="btn-group btn-group-sm" role="group">
                                <button type="button" class="btn btn-info" onclick="viewDetail({{ $skpt->id }})"
                                        data-toggle="tooltip" title="Lihat Detail">
                                    <i class="fas fa-eye"></i>
                                </button>
                                @if($skpt->dataPeninjauan && $skpt->dataPeninjauan->coordinates->count() > 0)
                                <button type="button" class="btn btn-success" onclick="focusOnMap({{ $skpt->id }})"
                                        data-toggle="tooltip" title="Lihat di Peta">
                                    <i class="fas fa-map-marker-alt"></i>
                                </button>
                                @endif
                                <button type="button" class="btn btn-warning" onclick="editData({{ $skpt->id }})"
                                        data-toggle="tooltip" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>

        <!-- Pagination (optional) -->
        @if($skptApplications->count() > 10)
        <nav aria-label="Page navigation" class="mt-3">
            <ul class="pagination justify-content-center">
                <li class="page-item disabled">
                    <a class="page-link" href="#" tabindex="-1">Previous</a>
                </li>
                <li class="page-item active"><a class="page-link" href="#">1</a></li>
                <li class="page-item"><a class="page-link" href="#">2</a></li>
                <li class="page-item"><a class="page-link" href="#">3</a></li>
                <li class="page-item">
                    <a class="page-link" href="#">Next</a>
                </li>
            </ul>
        </nav>
        @endif
    </div>
</div> --}}

<!-- Detail Modal -->
<div class="modal fade" id="detailModal" tabindex="-1" role="dialog" aria-labelledby="detailModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="detailModalLabel">
                    <i class="fas fa-file-alt mr-2"></i>Detail Permohonan SKPT
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div id="detailContent">
                    <!-- Content will be loaded here dynamically -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">
                    <i class="fas fa-times mr-1"></i>Tutup
                </button>
                {{-- <button type="button" class="btn btn-primary" onclick="printDetail()">
                    <i class="fas fa-print mr-1"></i>Cetak
                </button>
                <button type="button" class="btn btn-success" onclick="exportDetail()">
                    <i class="fas fa-file-pdf mr-1"></i>Export PDF
                </button> --}}
            </div>
        </div>
    </div>
</div>

<!-- Edit Modal (optional) -->
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
            <div class="modal-header bg-warning">
                <h5 class="modal-title" id="editModalLabel">
                    <i class="fas fa-edit mr-2"></i>Edit Data SKPT
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="editForm">
                    <div class="row">
                        <div class="col-md-6">
                            <h6 class="font-weight-bold text-primary mb-3">Data Pemohon</h6>
                            <div class="form-group">
                                <label for="edit_nama">Nama Pemohon <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="edit_nama" required>
                            </div>
                            <div class="form-group">
                                <label for="edit_nik">NIK <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="edit_nik" required maxlength="16">
                            </div>
                            <div class="form-group">
                                <label for="edit_no_hp">No. HP</label>
                                <input type="text" class="form-control" id="edit_no_hp">
                            </div>
                            <div class="form-group">
                                <label for="edit_alamat">Alamat Pemohon</label>
                                <textarea class="form-control" id="edit_alamat" rows="3"></textarea>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <h6 class="font-weight-bold text-primary mb-3">Data Tanah</h6>
                            <div class="form-group">
                                <label for="edit_alamat_tanah">Alamat Tanah <span class="text-danger">*</span></label>
                                <textarea class="form-control" id="edit_alamat_tanah" rows="3" required></textarea>
                            </div>
                            <div class="form-group">
                                <label for="edit_luas">Luas Tanah (m²) <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" id="edit_luas" required>
                            </div>
                            <div class="form-group">
                                <label for="edit_status">Status Permohonan</label>
                                <select class="form-control" id="edit_status">
                                    <option value="BELUM SELESAI">Belum Selesai</option>
                                    <option value="SELESAI">Selesai</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="edit_dokumen">Status Dokumen</label>
                                <select class="form-control" id="edit_dokumen">
                                    <option value="BELUM LENGKAP">Belum Lengkap</option>
                                    <option value="LENGKAP">Lengkap</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">
                    <i class="fas fa-times mr-1"></i>Batal
                </button>
                <button type="button" class="btn btn-primary" onclick="saveEdit()">
                    <i class="fas fa-save mr-1"></i>Simpan Perubahan
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title" id="deleteModalLabel">
                    <i class="fas fa-exclamation-triangle mr-2"></i>Konfirmasi Hapus
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>Apakah Anda yakin ingin menghapus data permohonan SKPT ini?</p>
                <div class="alert alert-warning">
                    <i class="fas fa-info-circle mr-2"></i>
                    Data yang sudah dihapus tidak dapat dikembalikan!
                </div>
                <div id="deleteInfo"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">
                    <i class="fas fa-times mr-1"></i>Batal
                </button>
                <button type="button" class="btn btn-danger" onclick="confirmDelete()">
                    <i class="fas fa-trash mr-1"></i>Hapus
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Loading Overlay for Page -->
<div id="pageLoading" class="loading-overlay d-none" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 9999;">
    <div class="text-center">
        <div class="spinner-border text-primary" style="width: 3rem; height: 3rem;" role="status">
            <span class="sr-only">Loading...</span>
        </div>
        <p class="mt-3 text-dark font-weight-bold">Memproses...</p>
    </div>
</div>

@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    // Global variables
    let map;
    let polygonLayers = {};
    let mapData = @json($mapData);
    let currentDetailId = null;
    // Table Data Management Variables
    let currentPage = 1;
    let isLoading = false;
    let hasMoreData = true;
    let allLoadedData = [];
    const itemsPerPage = 20;
    // Initialize on document ready
    $(document).ready(function() {
        // Initialize tooltips
        $('[data-toggle="tooltip"]').tooltip();

        // Initialize map
        initializeMap();

        // Calculate statistics
        calculateStats();

        // Setup event listeners
        setupEventListeners();
        initializeTableScroll();
        loadTableData(1);
         $('#searchInput').on('input', handleSearchInput);
        
        $('#statusFilter').on('change', function() {
            applyFilter();
        });
    });
    // Initialize infinite scroll
    function initializeTableScroll() {
        const tableContainer = document.getElementById('tableContainer');
        
        // Add scroll event listener
        tableContainer.addEventListener('scroll', function() {
            const scrollHeight = this.scrollHeight;
            const scrollTop = this.scrollTop;
            const clientHeight = this.clientHeight;
            
            // Check if scrolled to bottom (with 100px threshold)
            if (scrollTop + clientHeight >= scrollHeight - 100) {
                if (!isLoading && hasMoreData) {
                    loadTableData(currentPage + 1);
                }
            }
        });
    }

    // Load table data via AJAX
    function loadTableData(page) {
        if (isLoading) return;
        
        isLoading = true;
        $('#tableLoading').removeClass('d-none');
        
        $.ajax({
            url: '{{ route("skpt.getTableData") }}',
            type: 'GET',
            data: {
                page: page,
                per_page: itemsPerPage,
                search: $('#searchInput').val(),
                status: $('#statusFilter').val()
            },
            success: function(response) {
                if (response.success) {
                    // Append new data to table
                    appendTableRows(response.data, page);
                    
                    // Update counters
                    currentPage = page;
                    allLoadedData = allLoadedData.concat(response.data);
                    updateDataCounters();
                    
                    // Check if has more data
                    if (response.data.length < itemsPerPage) {
                        hasMoreData = false;
                        $('#noMoreData').removeClass('d-none');
                    }
                }
            },
            error: function(xhr, status, error) {
                console.error('Error loading data:', error);
                showNotification('Gagal memuat data', 'error');
            },
            complete: function() {
                isLoading = false;
                $('#tableLoading').addClass('d-none');
            }
        });
    }

    // Append rows to table
    function appendTableRows(data, page) {
        const tbody = $('#dataTableBody');
        const startIndex = (page - 1) * itemsPerPage;
        
        data.forEach(function(item, index) {
            const rowNumber = startIndex + index + 1;
            const statusBadge = item.status_permohonan === 'SELESAI' 
                ? '<span class="badge badge-success">Selesai</span>' 
                : '<span class="badge badge-warning">Belum Selesai</span>';
            
            // Format date
            const date = new Date(item.created_at);
            const formattedDate = date.toLocaleDateString('id-ID', {
                day: '2-digit',
                month: '2-digit', 
                year: 'numeric'
            });
            
            // Create row with data attributes
            const row = `
                <tr class="table-row-clickable" 
                    data-id="${item.id}"
                    data-has-coordinates="${item.has_coordinates}"
                    onclick="handleRowClick(${item.id}, ${item.has_coordinates})"
                    style="cursor: pointer;">
                    <td>${rowNumber}</td>
                    <td>
                        <small>
                            <strong>${item.jalan_gg_blok || '-'}</strong><br>
                            RT ${item.rt || '-'} RW ${item.rw || '-'}<br>
                            ${item.kecamatan || '-'}
                        </small>
                    </td>
                    <td>
                        <small>
                            <strong>${truncateText(item.nama_pemohon, 25)}</strong><br>
                            <span class="text-muted">${item.no_registrasi}</span>
                        </small>
                    </td>
                    <td>${formatNumber(item.luas)} m²</td>
                    <td>${statusBadge}</td>
                    <td><small>${formattedDate}</small></td>
                </tr>
            `;
            
            tbody.append(row);
        });
        
        // Add hover effect to new rows
        $('.table-row-clickable').hover(
            function() {
                $(this).addClass('table-active');
            },
            function() {
                $(this).removeClass('table-active');
            }
        );
    }

    // Update data counters
    function updateDataCounters() {
        $('#loadedCount').text(allLoadedData.length);
        // Total count should be set from backend
        $.ajax({
            url: '{{ route("skpt.getTotalCount") }}',
            type: 'GET',
            data: {
                search: $('#searchInput').val(),
                status: $('#statusFilter').val()
            },
            success: function(response) {
                $('#totalCount').text(response.total);
            }
        });
    }

    // Refresh table data
    function refreshTableData() {
        // Clear existing data
        $('#dataTableBody').empty();
        allLoadedData = [];
        currentPage = 1;
        hasMoreData = true;
        
        // Hide no more data message
        $('#noMoreData').addClass('d-none');
        
        // Reload first page
        loadTableData(1);
        
        showNotification('Data berhasil dimuat ulang', 'success');
    }

    // Helper function to truncate text
    function truncateText(text, maxLength) {
        if (!text) return '-';
        return text.length > maxLength ? text.substr(0, maxLength) + '...' : text;
    }

    // Helper function to format number
    function formatNumber(num) {
        return new Intl.NumberFormat('id-ID').format(num);
    }
    // Handle table row click
function handleRowClick(id, hasCoordinates) {
    // Remove previous highlight
    $('.table-row-clickable').removeClass('table-primary');
    
    // Add highlight to clicked row
    $(`tr[data-id="${id}"]`).addClass('table-primary');
    
    // Check if has coordinates
    if (hasCoordinates) {
        // Focus on polygon in map
        focusOnMapFromTable(id);
        
        // Scroll to map if on mobile or small screen
        if (window.innerWidth < 992) {
            $('html, body').animate({
                scrollTop: $('#map').offset().top - 80
            }, 500);
        }
    } else {
        // Show notification that no coordinates available
        showNotification('Data koordinat tidak tersedia untuk lokasi ini', 'warning');
        
        // Load detail in modal instead
        viewDetailFromTable(id);
    }
}

// Enhanced focus on map function for table integration
function focusOnMapFromTable(id) {
    // Check if polygon exists in current loaded polygons
    if (polygonLayers[id]) {
        // Use existing polygon
        focusOnExistingPolygon(id);
    } else {
        // Load polygon data via AJAX
        loadPolygonData(id);
    }
}

// Focus on existing polygon
function focusOnExistingPolygon(id) {
    const polygon = polygonLayers[id];
    
    // Animate map pan and zoom
    map.fitBounds(polygon.getBounds(), {
        padding: [100, 100],
        maxZoom: 30,
        animate: true,
        duration: 1
    });
    
    // Add pulse effect to polygon
    addPulseEffect(polygon);
    
    // Open popup after animation
    setTimeout(function() {
        polygon.openPopup();
    }, 1000);
}

// Load polygon data via AJAX
function loadPolygonData(id) {
    // Show loading on map
    $('#mapLoading').removeClass('d-none');
    
    $.ajax({
        url: '{{ route("skpt.getPolygonData") }}',
        type: 'GET',
        data: { id: id },
        success: function(response) {
            if (response.success && response.coordinates) {
                // Add polygon to map
                addSinglePolygon(response);
                
                // Focus on the new polygon
                setTimeout(function() {
                    focusOnExistingPolygon(id);
                }, 100);
            } else {
                showNotification('Koordinat tidak ditemukan', 'warning');
            }
        },
        error: function(xhr, status, error) {
            console.error('Error loading polygon:', error);
            showNotification('Gagal memuat data peta', 'error');
        },
        complete: function() {
            $('#mapLoading').addClass('d-none');
        }
    });
}

// Add single polygon to map
function addSinglePolygon(data) {
    if (data.coordinates && data.coordinates.length > 0) {
        // Prepare coordinates
        const coords = data.coordinates.map(c => [c.lat, c.lng]);
        
        // Determine color based on status
        const color = data.status === 'SELESAI' ? '#28a745' : '#ffc107';
        
        // Create polygon
        const polygon = L.polygon(coords, {
            color: color,
            weight: 2,
            opacity: 0.8,
            fillColor: color,
            fillOpacity: 0.35
        }).addTo(map);
        
        // Create enhanced popup content
        const popupContent = createEnhancedPopupContent(data);
        
        // Bind popup
        polygon.bindPopup(popupContent, {
            maxWidth: 350,
            className: 'custom-popup'
        });
        
        // Add hover effects
        polygon.on('mouseover', function() {
            this.setStyle({
                weight: 3,
                fillOpacity: 0.5
            });
        });
        
        polygon.on('mouseout', function() {
            this.setStyle({
                weight: 2,
                fillOpacity: 0.35
            });
        });
        
        // Store polygon reference
        polygonLayers[data.id] = polygon;
    }
}

// Create enhanced popup content
function createEnhancedPopupContent(data) {
    return `
        <div style="min-width: 280px;">
            <h6 class="mb-2 font-weight-bold">${data.nama_pemohon}</h6>
            <table class="table table-sm table-borderless mb-2">
                <tr>
                    <td class="text-muted">No. Reg:</td>
                    <td class="font-weight-medium">${data.no_registrasi}</td>
                </tr>
                <tr>
                    <td class="text-muted">NIK:</td>
                    <td>${data.nik || '-'}</td>
                </tr>
                <tr>
                    <td class="text-muted">Status:</td>
                    <td>
                        <span class="badge badge-${data.status === 'SELESAI' ? 'success' : 'warning'}">
                            ${data.status}
                        </span>
                    </td>
                </tr>
                <tr>
                    <td class="text-muted">Luas:</td>
                    <td>${formatNumber(data.luas)} m²</td>
                </tr>
                <tr>
                    <td class="text-muted">Kecamatan:</td>
                    <td>${data.kecamatan || '-'}</td>
                </tr>
                <tr>
                    <td class="text-muted">Alamat:</td>
                    <td><small>${data.alamat || '-'}</small></td>
                </tr>
                <tr>
                    <td class="text-muted">Tanggal:</td>
                    <td><small>${formatDate(data.created_at)}</small></td>
                </tr>
            </table>
            <div class="d-flex justify-content-between">
                <button class="btn btn-sm btn-primary" onclick="viewDetail(${data.id})">
                    <i class="fas fa-eye mr-1"></i>Detail
                </button>
                <button class="btn btn-sm btn-warning" onclick="editData(${data.id})">
                    <i class="fas fa-edit mr-1"></i>Edit
                </button>
                <button class="btn btn-sm btn-info" onclick="printSingleData(${data.id})">
                    <i class="fas fa-print mr-1"></i>Print
                </button>
            </div>
        </div>
    `;
}

// Add pulse effect to polygon
function addPulseEffect(polygon) {
    let pulseCount = 0;
    const originalStyle = {
        weight: polygon.options.weight,
        fillOpacity: polygon.options.fillOpacity
    };
    
    const pulseInterval = setInterval(function() {
        if (pulseCount % 2 === 0) {
            polygon.setStyle({
                weight: 4,
                fillOpacity: 0.6
            });
        } else {
            polygon.setStyle(originalStyle);
        }
        
        pulseCount++;
        
        // Stop after 6 pulses (3 seconds)
        if (pulseCount >= 6) {
            clearInterval(pulseInterval);
            polygon.setStyle(originalStyle);
        }
    }, 500);
}
// Enhanced detail loading function
function loadDetailContent(item) {
    // Show loading state
    $('#detailContent').html(`
        <div class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="sr-only">Loading...</span>
            </div>
            <p class="mt-2">Memuat detail data...</p>
        </div>
    `);
    
    // Load detail via AJAX
    $.ajax({
        url: '{{ route("skpt.getDetailData") }}',
        type: 'GET',
        data: { id: item.id },
        success: function(response) {
            if (response.success) {
                displayDetailContent(response);
            }
        },
        error: function(xhr, status, error) {
            $('#detailContent').html(`
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle mr-2"></i>
                    Gagal memuat detail data
                </div>
            `);
        }
    });
}

// Display detail content in modal
function displayDetailContent(data) {
    const statusBadge = data.status.permohonan === 'SELESAI' 
        ? '<span class="badge badge-success">Selesai</span>' 
        : '<span class="badge badge-warning">Belum Selesai</span>';
    
    const dokumenBadge = data.status.dokumen === 'LENGKAP'
        ? '<span class="badge badge-info">Lengkap</span>'
        : '<span class="badge badge-danger">Belum Lengkap</span>';
    
    const detailHtml = `
        <div class="row">
            <!-- Pemohon Information -->
            <div class="col-md-6">
                <div class="card mb-3">
                    <div class="card-header bg-light">
                        <h6 class="mb-0 text-primary">
                            <i class="fas fa-user mr-2"></i>Data Pemohon
                        </h6>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm table-borderless">
                            <tr>
                                <td width="40%" class="text-muted">No. Registrasi</td>
                                <td>: <strong>${data.pemohon.no_registrasi}</strong></td>
                            </tr>
                            <tr>
                                <td class="text-muted">Nama</td>
                                <td>: ${data.pemohon.nama}</td>
                            </tr>
                            <tr>
                                <td class="text-muted">NIK</td>
                                <td>: ${data.pemohon.nik}</td>
                            </tr>
                            <tr>
                                <td class="text-muted">No. HP</td>
                                <td>: ${data.pemohon.no_hp || '-'}</td>
                            </tr>
                            <tr>
                                <td class="text-muted">Alamat</td>
                                <td>: ${data.pemohon.alamat || '-'}</td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
            
            <!-- Tanah Information -->
            <div class="col-md-6">
                <div class="card mb-3">
                    <div class="card-header bg-light">
                        <h6 class="mb-0 text-primary">
                            <i class="fas fa-map-marked-alt mr-2"></i>Data Tanah
                        </h6>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm table-borderless">
                            <tr>
                                <td width="40%" class="text-muted">Alamat</td>
                                <td>: ${data.tanah.alamat}</td>
                            </tr>
                            <tr>
                                <td class="text-muted">RT/RW</td>
                                <td>: ${data.tanah.rt}/${data.tanah.rw}</td>
                            </tr>
                            <tr>
                                <td class="text-muted">Kelurahan</td>
                                <td>: ${data.tanah.kelurahan}</td>
                            </tr>
                            <tr>
                                <td class="text-muted">Kecamatan</td>
                                <td>: ${data.tanah.kecamatan}</td>
                            </tr>
                            <tr>
                                <td class="text-muted">Luas</td>
                                <td>: <strong>${formatNumber(data.tanah.luas)} m²</strong></td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Batas Tanah -->
        <div class="card mb-3">
            <div class="card-header bg-light">
                <h6 class="mb-0 text-primary">
                    <i class="fas fa-border-all mr-2"></i>Batas Tanah
                </h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-6">
                        <small class="text-muted">Utara:</small><br>
                        ${data.tanah.batas_utara}
                    </div>
                    <div class="col-6">
                        <small class="text-muted">Selatan:</small><br>
                        ${data.tanah.batas_selatan}
                    </div>
                    <div class="col-6 mt-2">
                        <small class="text-muted">Timur:</small><br>
                        ${data.tanah.batas_timur}
                    </div>
                    <div class="col-6 mt-2">
                        <small class="text-muted">Barat:</small><br>
                        ${data.tanah.batas_barat}
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Status Information -->
        <div class="card">
            <div class="card-header bg-light">
                <h6 class="mb-0 text-primary">
                    <i class="fas fa-info-circle mr-2"></i>Status
                </h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-6">
                        <small class="text-muted">Status Permohonan:</small><br>
                        ${statusBadge}
                    </div>
                    <div class="col-6">
                        <small class="text-muted">Status Dokumen:</small><br>
                        ${dokumenBadge}
                    </div>
                    <div class="col-6 mt-3">
                        <small class="text-muted">Tanggal Permohonan:</small><br>
                        ${data.status.tanggal_permohonan}
                    </div>
                    <div class="col-6 mt-3">
                        <small class="text-muted">Terakhir Update:</small><br>
                        ${data.status.tanggal_update}
                    </div>
                </div>
            </div>
        </div>
    `;
    
    $('#detailContent').html(detailHtml);
}

// Load detail via AJAX when not in loaded data
function loadDetailViaAjax(id) {
    $('#detailModal').modal('show');
    loadDetailContent({ id: id });
}
// View detail from table click (when no coordinates)
function viewDetailFromTable(id) {
    // Get data from loaded data
    const item = allLoadedData.find(d => d.id === id);
    
    if (item) {
        // Show detail modal with animation
        $('#detailModal').modal({
            backdrop: 'static',
            keyboard: false,
            show: true
        });
        
        // Load detail content
        loadDetailContent(item);
    } else {
        // Load via AJAX if not in loaded data
        loadDetailViaAjax(id);
    }
}

// Format date helper
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('id-ID', {
        day: '2-digit',
        month: 'long',
        year: 'numeric'
    });
}

    // Initialize Leaflet Map
    function initializeMap() {
        // Create map with default view (Balikpapan, Indonesia)
        map = L.map('map', {
            center: [-1.2379, 116.8529],
            zoom: 11,
            zoomControl: false
        });

        // Add zoom control to topright
        L.control.zoom({
            position: 'topright'
        }).addTo(map);

        // Add OpenStreetMap tiles
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 19,
            attribution: '© OpenStreetMap contributors'
        }).addTo(map);

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

        // Load initial polygons
        loadPolygons(mapData);
    }

    // Load polygons to map
    function loadPolygons(data) {
        // Clear existing polygons
        for(let id in polygonLayers) {
            map.removeLayer(polygonLayers[id]);
        }
        polygonLayers = {};

        let bounds = [];

        // Add each polygon
        data.forEach(function(item) {
            if(item.coordinates && item.coordinates.length > 0) {
                // Prepare coordinates
                let coords = item.coordinates.map(c => [c.lat, c.lng]);

                // Create polygon with styling
                let polygon = L.polygon(coords, {
                    color: item.color,
                    weight: 2,
                    opacity: 0.8,
                    fillColor: item.color,
                    fillOpacity: 0.35
                }).addTo(map);

                // Add coordinates to bounds
                bounds = bounds.concat(coords);

                // Create popup content with Bootstrap styling
                let popupContent = `
                    <div style="min-width: 280px;">
                        <h6 class="mb-2 font-weight-bold">${item.nama_pemohon}</h6>
                        <table class="table table-sm table-borderless mb-2">
                            <tr>
                                <td class="text-muted">No. Reg:</td>
                                <td class="font-weight-medium">${item.no_registrasi}</td>
                            </tr>
                            <tr>
                                <td class="text-muted">Status:</td>
                                <td>
                                    <span class="badge badge-${item.status === 'SELESAI' ? 'success' : 'warning'}">
                                        ${item.status}
                                    </span>
                                </td>
                            </tr>
                            <tr>
                                <td class="text-muted">Luas:</td>
                                <td>${formatNumber(item.luas)} m²</td>
                            </tr>
                            <tr>
                                <td class="text-muted">Kecamatan:</td>
                                <td>${item.kecamatan || '-'}</td>
                            </tr>
                            <tr>
                                <td class="text-muted">Alamat:</td>
                                <td><small>${item.alamat || '-'}</small></td>
                            </tr>
                        </table>
                        <div class="d-flex justify-content-between">
                            <button class="btn btn-sm btn-primary" onclick="viewDetail(${item.id})">
                                <i class="fas fa-eye mr-1"></i>Detail
                            </button>
                            <button class="btn btn-sm btn-warning" onclick="editData(${item.id})">
                                <i class="fas fa-edit mr-1"></i>Edit
                            </button>
                        </div>
                    </div>
                `;

                // Bind popup
                polygon.bindPopup(popupContent, {
                    maxWidth: 350,
                    className: 'custom-popup'
                });

                // Add hover effects
                polygon.on('mouseover', function() {
                    this.setStyle({
                        weight: 3,
                        fillOpacity: 0.5
                    });
                });

                polygon.on('mouseout', function() {
                    this.setStyle({
                        weight: 2,
                        fillOpacity: 0.35
                    });
                });

                // Store polygon reference
                polygonLayers[item.id] = polygon;
            }
        });

        // Fit map to all polygons if exists
        if(bounds.length > 0) {
            map.fitBounds(bounds, { padding: [50, 50] });
        }
    }

    // Setup event listeners
    function setupEventListeners() {
        // Search input with debounce
        let searchTimeout;
        $('#searchInput').on('keyup', function() {
            clearTimeout(searchTimeout);
            let value = $(this).val();
            searchTimeout = setTimeout(function() {
                if(value.length >= 3 || value.length === 0) {
                    applyFilter();
                }
            }, 500);
        });

        // Status filter change
        $('#statusFilter').on('change', function() {
            applyFilter();
        });

        // Date filters
        $('#dateFrom, #dateTo').on('change', function() {
            if($('#dateFrom').val() && $('#dateTo').val()) {
                applyFilter();
            }
        });
    }

    // // Apply filters via AJAX
    // function applyFilter() {
    //     // Show loading
    //     $('#mapLoading').removeClass('d-none');

    //     // Prepare filter data
    //     let filterData = {
    //         search: $('#searchInput').val(),
    //         status: $('#statusFilter').val(),
    //         date_from: $('#dateFrom').val(),
    //         date_to: $('#dateTo').val(),
    //         _token: '{{ csrf_token() }}'
    //     };

    //     // Send AJAX request
    //     $.ajax({
    //         url: '{{ route("filter.skpt") }}',
    //         type: 'POST',
    //         data: filterData,
    //         success: function(response) {
    //             if(response.success) {
    //                 // Reload polygons
    //                 loadPolygons(response.data);

    //                 // Update count
    //                 $('#dataCount').text(response.count);

    //                 // Show success notification
    //                 showNotification('Filter berhasil diterapkan', 'success');
    //             }
    //             $('#mapLoading').addClass('d-none');
    //         },
    //         error: function(xhr, status, error) {
    //             console.error('Filter error:', error);
    //             showNotification('Gagal menerapkan filter', 'error');
    //             $('#mapLoading').addClass('d-none');
    //         }
    //     });
    // }
    // Enhanced filter functionality integrated with table
// function applyFilter() {
//     // Show loading on both map and table
//     $('#mapLoading').removeClass('d-none');
//     $('#pageLoading').removeClass('d-none');
    
//     // Reset table data
//     $('#dataTableBody').empty();
//     allLoadedData = [];
//     currentPage = 1;
//     hasMoreData = true;
//     $('#noMoreData').addClass('d-none');
    
//     // Prepare filter data
//     const filterData = {
//         search: $('#searchInput').val(),
//         status: $('#statusFilter').val(),
//         date_from: $('#dateFrom').val(),
//         date_to: $('#dateTo').val(),
//         _token: '{{ csrf_token() }}'
//     };
    
//     // Apply filter to map
//     $.ajax({
//         url: '{{ route("filter.skpt") }}',
//         type: 'POST',
//         data: filterData,
//         success: function(response) {
//             if (response.success) {
//                 // Reload polygons on map
//                 loadPolygons(response.data);
                
//                 // Show success notification
//                 showNotification(`Filter diterapkan: ${response.count} data ditemukan`, 'success');
//             }
//             $('#mapLoading').addClass('d-none');
//         },
//         error: function(xhr, status, error) {
//             console.error('Filter error:', error);
//             showNotification('Gagal menerapkan filter pada peta', 'error');
//             $('#mapLoading').addClass('d-none');
//         }
//     });
    
//     // Reload table with filter
//     loadTableData(1);
//     $('#pageLoading').addClass('d-none');
// }
// Enhanced filter functionality integrated with table
function applyFilter() {
    // Show loading on both map and table
    $('#mapLoading').removeClass('d-none');
    $('#pageLoading').removeClass('d-none');
    
    // Reset table data
    $('#dataTableBody').empty();
    allLoadedData = [];
    currentPage = 1;
    hasMoreData = true;
    $('#noMoreData').addClass('d-none');
    
    // Prepare filter data
    const filterData = {
        search: $('#searchInput').val(),
        status: $('#statusFilter').val(),
        date_from: $('#dateFrom').val(),
        date_to: $('#dateTo').val(),
        _token: '{{ csrf_token() }}'
    };
    
    // Apply filter to map
    $.ajax({
        url: '{{ route("filter.skpt") }}',
        type: 'POST',
        data: filterData,
        success: function(response) {
            if (response.success) {
                // Reload polygons on map
                loadPolygons(response.data);
                
                // Show success notification
                showNotification(`Filter diterapkan: ${response.count} data ditemukan`, 'success');
            }
            $('#mapLoading').addClass('d-none');
        },
        error: function(xhr, status, error) {
            console.error('Filter error:', error);
            showNotification('Gagal menerapkan filter pada peta', 'error');
            $('#mapLoading').addClass('d-none');
        }
    });
    
    // Reload table with filter
    loadTableData(1);
    $('#pageLoading').addClass('d-none');
}

// Enhanced reset filter
// function resetFilter() {
//     // Reset form inputs
//     $('#searchInput').val('');
//     $('#statusFilter').val('all');
//     $('#dateFrom').val('');
//     $('#dateTo').val('');
    
//     // Clear table highlights
//     $('.table-row-clickable').removeClass('table-primary');
    
//     // Reload both map and table
//     refreshMapAndTable();
    
//     showNotification('Filter berhasil direset', 'info');
// }
// Enhanced reset filter
function resetFilter() {
    // Reset form inputs
    $('#searchInput').val('');
    $('#statusFilter').val('all');
    $('#dateFrom').val('');
    $('#dateTo').val('');
    
    // Clear table highlights
    $('.table-row-clickable').removeClass('table-primary');
    
    // Reload both map and table
    refreshMapAndTable();
    
    showNotification('Filter berhasil direset', 'info');
}
// Refresh both map and table
function refreshMapAndTable() {
    // Refresh map
    loadPolygons(mapData);
    
    // Refresh table
    refreshTableData();
}

// Search with debounce
let searchTimeout;
function handleSearchInput() {
    clearTimeout(searchTimeout);
    const searchValue = $('#searchInput').val();
    
    searchTimeout = setTimeout(function() {
        if (searchValue.length >= 3 || searchValue.length === 0) {
            // Apply filter to both map and table
            applyFilter();
        }
    }, 500);
}

// Bind enhanced search functionality
$(document).ready(function() {
    $('#searchInput').on('input', handleSearchInput);
    
    $('#statusFilter').on('change', function() {
        applyFilter();
    });
});

    // Reset all filters
    function resetFilter() {
        $('#searchInput').val('');
        $('#statusFilter').val('all');
        $('#dateFrom').val('');
        $('#dateTo').val('');

        // Reload original data
        loadPolygons(mapData);

        showNotification('Filter berhasil direset', 'info');
    }

    // Focus on specific polygon
    function focusOnMap(id) {
        if(polygonLayers[id]) {
            let polygon = polygonLayers[id];

            // Fit bounds to polygon
            map.fitBounds(polygon.getBounds(), {
                padding: [100, 100],
                maxZoom: 16
            });

            // Open popup
            setTimeout(function() {
                polygon.openPopup();
            }, 500);

            // Highlight effect
            polygon.setStyle({
                weight: 4,
                fillOpacity: 0.6
            });

            // Reset style after 3 seconds
            setTimeout(function() {
                polygon.setStyle({
                    weight: 2,
                    fillOpacity: 0.35
                });
            }, 3000);

            // Scroll to map if needed
            $('html, body').animate({
                scrollTop: $('#map').offset().top - 100
            }, 500);
        } else {
            showNotification('Lokasi tidak ditemukan pada peta', 'warning');
        }
    }

    // View detail modal
    function viewDetail(id) {
        currentDetailId = id;

        // Show loading in modal
        $('#detailContent').html(`
            <div class="text-center py-5">
                <div class="spinner-border text-primary" role="status">
                    <span class="sr-only">Loading...</span>
                </div>
                <p class="mt-2">Memuat data...</p>
            </div>
        `);

        // Show modal
        $('#detailModal').modal('show');

        // Load detail content (simulate with existing data)
        setTimeout(function() {
            let item = mapData.find(d => d.id === id);
            if(item) {
                $('#detailContent').html(`
                    <div class="row">
                        <div class="col-md-6">
                            <h6 class="font-weight-bold text-primary mb-3">Informasi Pemohon</h6>
                            <table class="table table-sm">
                                <tr>
                                    <td width="40%">No. Registrasi</td>
                                    <td>: <strong>${item.no_registrasi}</strong></td>
                                </tr>
                                <tr>
                                    <td>Nama Pemohon</td>
                                    <td>: ${item.nama_pemohon}</td>
                                </tr>
                                <tr>
                                    <td>Status Permohonan</td>
                                    <td>: <span class="badge badge-${item.status === 'SELESAI' ? 'success' : 'warning'}">
                                        ${item.status}
                                    </span></td>
                                </tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <h6 class="font-weight-bold text-primary mb-3">Informasi Tanah</h6>
                            <table class="table table-sm">
                                <tr>
                                    <td width="40%">Luas Tanah</td>
                                    <td>: ${formatNumber(item.luas)} m²</td>
                                </tr>
                                <tr>
                                    <td>Kecamatan</td>
                                    <td>: ${item.kecamatan || '-'}</td>
                                </tr>
                                <tr>
                                    <td>Alamat</td>
                                    <td>: ${item.alamat || '-'}</td>
                                </tr>
                            </table>
                        </div>
                    </div>
                `);
            }
        }, 1000);
    }

    // Edit data
    function editData(id) {
        window.location.href = `/skpt/${id}/edit`;
    }

    // Export data
    function exportData() {
        Swal.fire({
            title: 'Export Data',
            text: 'Pilih format export:',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Excel',
            cancelButtonText: 'PDF',
            showDenyButton: true,
            denyButtonText: 'CSV'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = '/export/excel';
            } else if (result.isDenied) {
                window.location.href = '/export/csv';
            } else if (result.dismiss === Swal.DismissReason.cancel) {
                window.location.href = '/export/pdf';
            }
        });
    }

    // Print detail
    function printDetail() {
        window.print();
    }

    // Toggle fullscreen
    function toggleFullscreen() {
        let mapElement = document.getElementById('map');
        if (!document.fullscreenElement) {
            mapElement.requestFullscreen().then(() => {
                setTimeout(() => map.invalidateSize(), 100);
            });
        } else {
            document.exitFullscreen();
        }
    }

    // Refresh map
    function refreshMap() {
        $('#mapLoading').removeClass('d-none');

        setTimeout(function() {
            map.invalidateSize();
            loadPolygons(mapData);
            $('#mapLoading').addClass('d-none');
            showNotification('Peta berhasil dimuat ulang', 'success');
        }, 1000);
    }

    // Toggle map view
    function toggleMapView() {
        $('#mapSection').toggle('slide');
        let text = $('#mapSection').is(':visible') ? 'Sembunyikan Peta' : 'Tampilkan Peta';
        $('#mapToggleText').text(text);

        if($('#mapSection').is(':visible')) {
            setTimeout(() => map.invalidateSize(), 300);
        }
    }

    // Calculate statistics
    function calculateStats() {
        let totalArea = 0;
        let todayCount = 0;
        let today = new Date().toDateString();

        @foreach($skptApplications as $skpt)
            totalArea += {{ $skpt->luas ?? 0 }};
            @if($skpt->created_at->isToday())
                todayCount++;
            @endif
        @endforeach

        $('#totalArea').text(formatNumber(Math.round(totalArea)) + ' m²');
        $('#todayCount').text(todayCount);
    }

    // Helper function: format number
    function formatNumber(num) {
        return new Intl.NumberFormat('id-ID').format(num);
    }

    // Show notification
    function showNotification(message, type) {
        Swal.fire({
            toast: true,
            position: 'top-end',
            icon: type,
            title: message,
            showConfirmButton: false,
            timer: 3000,
            timerProgressBar: true,
            didOpen: (toast) => {
                toast.addEventListener('mouseenter', Swal.stopTimer)
                toast.addEventListener('mouseleave', Swal.resumeTimer)
            }
        });
    }
</script>
@endpush
