@extends('admin-layouts.master')

@section('title', 'Daftar Surat Pernyataan Melepaskan Penguasaan Tanah (SP-MPT)')

@section('content')
<div class="row">
    <div class="col-12">
        <!-- Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h2 class="h4 mb-1">Daftar Surat Pernyataan Melepaskan Penguasaan Tanah (SP-MPT)</h2>
                <p class="text-muted mb-0">Kelola semua permohonan Surat Pernyataan Melepaskan Penguasaan Tanah</p>
            </div>
            <a href="{{ route('sp-sipt.create') }}" class="btn btn-primary">
                <i class="fas fa-plus"></i> Tambah Permohonan
            </a>
        </div>

        <!-- Stats Cards -->
        <div class="row mb-4">
            <div class="col-md-2">
                <div class="card border-left-primary shadow h-100 py-2">
                    <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 Pengajuan</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $statistics['total'] ?? 0 }}</div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-file-alt fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card border-left-secondary shadow h-100 py-2">
                    <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-secondary text-uppercase mb-1">
                                    Draft</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $statistics['draft'] ?? 0 }}</div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-edit fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card border-left-warning shadow h-100 py-2">
                    <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">{{ $statistics['submitted'] ?? 0 }}</div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-clock fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card border-left-info shadow h-100 py-2">
                    <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">
                                    Sedang Ditinjau</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $statistics['in_review'] ?? 0 }}</div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-search fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card border-left-success shadow h-100 py-2">
                    <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">{{ $statistics['approved'] ?? 0 }}</div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-check-circle fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card border-left-danger shadow h-100 py-2">
                    <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">
                                    Ditolak</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $statistics['rejected'] ?? 0 }}</div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-times-circle fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filter & Search -->
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">Filter & Pencarian</h6>
            </div>
            <div class="card-body">
                <form method="GET" action="{{ route('sp-sipt.index') }}" class="row" id="filterForm">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="search">Pencarian</label>
                            <input type="text" class="form-control form-control-sm" 
                                   id="search" name="search" 
                                   placeholder="NIK, Nama, atau No. Registrasi"
                                   value="{{ request('search') }}">
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            <label for="year">Tahun</label>
                            <select class="form-control form-control-sm" id="year" name="year">
                                <option value="{{ date('Y') }}" {{ request('year', date('Y')) == date('Y') ? 'selected' : '' }}>
                                    {{ date('Y') }}
                                </option>
                                @for($i = date('Y') - 1; $i >= date('Y') - 5; $i--)
                                    <option value="{{ $i }}" {{ request('year') == $i ? 'selected' : '' }}>
                                        {{ $i }}
                                    </option>
                                @endfor
                            </select>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="status">Status</label>
                            <select class="form-control form-control-sm" id="status" name="status">
                                <option value="">Semua Status</option>
                                <option value="draft" {{ request('status') == 'draft' ? 'selected' : '' }}>Draft</option>
                                <option value="submitted" {{ request('status') == 'submitted' ? 'selected' : '' }}>Belum Selesai</option>
                                <option value="in_review" {{ request('status') == 'in_review' ? 'selected' : '' }}>Sedang Ditinjau</option>
                                <option value="approved" {{ request('status') == 'approved' ? 'selected' : '' }}>Selesai</option>
                                <option value="rejected" {{ request('status') == 'rejected' ? 'selected' : '' }}>Ditolak</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="kelurahan">Kelurahan</label>
                            <input type="text" class="form-control form-control-sm" 
                                   id="kelurahan" name="kelurahan" 
                                   placeholder="Nama Kelurahan"
                                   value="{{ request('kelurahan') }}">
                        </div>
                    </div>
                    <div class="col-md-1">
                        <div class="form-group">
                            <label>&nbsp;</label>
                            <div>
                                <button type="submit" class="btn btn-primary btn-sm">
                                    <i class="fas fa-search"></i>
                                </button>
                                <a href="{{ route('sp-sipt.index') }}" class="btn btn-secondary btn-sm ml-1">
                                    <i class="fas fa-times"></i>
                                </a>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- Data Table -->
        <div class="card shadow mb-4">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">Data Surat Pernyataan Melepaskan Penguasaan Tanah</h6>
                <button class="btn btn-success btn-sm" onclick="window.print()">
                    <i class="fas fa-print"></i> Cetak Laporan
                </button>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-hover">
                        <thead class="thead-light">
                            <tr>
                                <th width="15%">NIK/No. Registrasi</th>
                                <th width="20%">Pemohon</th>
                                <th width="15%">Tanggal Masuk</th>
                                <th width="15%">Status</th>
                                <th width="20%">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($spSipts as $spSipt)
                            <tr>
                                <td>
                                    <div class="font-weight-bold text-primary">{{ $spSipt->pemohon_nik }}</div>
                                    <small class="text-muted">{{ $spSipt->nomor_surat ?? 'XXX-XXX-XXX' }}</small>
                                </td>
                                <td>
                                    <div class="font-weight-bold">{{ $spSipt->pemohon_nama }}</div>
                                    <small class="text-muted">{{ $spSipt->created_at->format('d/m/Y') }}</small>
                                </td>
                                <td>
                                    <small>{{ $spSipt->created_at->format('d/m/Y') }}</small>
                                </td>
                                <td>
                                    @switch($spSipt->status)
                                        @case('draft')
                                            <span class="badge badge-secondary">
                                                <i class="fas fa-edit"></i> Draft
                                            </span>
                                            @break
                                        @case('submitted')
                                            <span class="badge badge-warning">
                                                <i class="fas fa-clock"></i> Belum Selesai
                                            </span>
                                            @break
                                        @case('in_review')
                                            <span class="badge badge-info">
                                                <i class="fas fa-search"></i> Sedang Ditinjau
                                            </span>
                                            @break
                                        @case('approved')
                                            <span class="badge badge-success">
                                                <i class="fas fa-check-circle"></i> Selesai
                                            </span>
                                            @break
                                        @case('rejected')
                                            <span class="badge badge-danger">
                                                <i class="fas fa-times-circle"></i> Ditolak
                                            </span>
                                            @break
                                        @default
                                            <span class="badge badge-secondary">
                                                {{ strtoupper($spSipt->status) }}
                                            </span>
                                    @endswitch
                                </td>
                                <td>
                                    <div class="btn-group" role="group">
                                        <a href="#" 
                                        class="btn btn-sm btn-outline-primary view-detail" 
                                        data-toggle="tooltip" title="Lihat Detail"
                                        data-id="{{ $spSipt->id }}"
                                        data-name="{{ $spSipt->pemohon_nama }}"
                                        data-nik="{{ $spSipt->pemohon_nik }}"
                                        data-nomor-ba="{{ $spSipt->nomor_surat }}"
                                        data-status="{{ $spSipt->status }}">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <a href="{{ route('sp-sipt.edit', $spSipt) }}" 
                                           class="btn btn-sm btn-outline-warning"
                                           data-toggle="tooltip" title="Edit">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <a href="{{ route('sp-sipt.print', $spSipt) }}" 
                                           target="_blank"
                                           class="btn btn-sm btn-outline-info"
                                           data-toggle="tooltip" title="Cetak">
                                            <i class="fas fa-print"></i>
                                        </a>
                                        @if($spSipt->status === 'draft')
                                        <button type="button" 
                                                class="btn btn-sm btn-outline-danger" 
                                                data-toggle="tooltip" title="Hapus"
                                                onclick="confirmDelete('{{ $spSipt->pemohon_nama }}', '{{ route('sp-sipt.destroy', $spSipt) }}')">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                        @endif
                                        @if($spSipt->status !== 'approved')
                                        <button type="button" 
                                                class="btn btn-sm btn-outline-success update-status" 
                                                data-toggle="tooltip" title="Tandai Selesai"
                                                data-id="{{ $spSipt->id }}"
                                                data-status="approved">
                                            <i class="fas fa-check"></i>
                                        </button>
                                        @endif
                                        @if($spSipt->status === 'approved')
                                        <button type="button" 
                                                class="btn btn-sm btn-outline-warning update-status" 
                                                data-toggle="tooltip" title="Tandai Belum Selesai"
                                                data-id="{{ $spSipt->id }}"
                                                data-status="submitted">
                                            <i class="fas fa-times"></i>
                                        </button>
                                        @endif
                                    </div>
                                </td>
                            </tr>
                            @empty
                            <tr>
                                <td colspan="5" class="text-center py-4">
                                    <div class="text-muted">
                                        <i class="fas fa-inbox fa-3x mb-3"></i>
                                        <h5>Tidak ada data</h5>
                                        <p>Belum ada permohonan SP-MPT yang tersedia</p>
                                        <a href="{{ route('sp-sipt.create') }}" class="btn btn-primary">
                                            <i class="fas fa-plus"></i> Tambah Permohonan Pertama
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                @if($spSipts->hasPages())
                <div class="d-flex justify-content-between align-items-center mt-3">
                    <div class="showing-info">
                        <small class="text-muted">
                            Menampilkan {{ $spSipts->firstItem() }} - {{ $spSipts->lastItem() }} 
                            dari {{ $spSipts->total() }} data
                        </small>
                    </div>
                    {{ $spSipts->withQueryString()->links('pagination::bootstrap-4') }}
                </div>
                @endif
            </div>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Konfirmasi Hapus</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>Apakah Anda yakin ingin menghapus permohonan SP-MPT <strong id="deleteItemName"></strong>?</p>
                <p class="text-danger"><small>Tindakan ini tidak dapat dibatalkan dan akan menghapus semua dokumen terkait.</small></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
                <form id="deleteForm" method="POST" style="display: inline;">
                    @csrf
                    @method('DELETE')
                    <button type="submit" class="btn btn-danger">
                        <i class="fas fa-trash"></i> Hapus
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>
<!-- Detail Modal -->
<div class="modal fade" id="detailModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header" style="background: linear-gradient(135deg, #28a745 0%, #20c997 100%); color: white;">
                <div class="w-100">
                    <div class="text-center">
                        <div style="background: #28a745; color: white; padding: 4px 12px; border-radius: 15px; font-size: 11px; font-weight: bold; display: inline-block; margin-bottom: 10px;">
                            DOKUMEN RESMI
                        </div>
                    </div>
                    <h5 class="modal-title text-center mb-0" id="detailModalTitle"></h5>
                    <p class="text-center mb-0 mt-1" style="font-size: 13px; opacity: 0.9;" id="detailModalSubtitle"></p>
                </div>
                <button type="button" class="close text-white" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            
            <div class="modal-body">
                <div style="background: #e8f5e8; border-left: 4px solid #28a745; padding: 10px; margin-bottom: 15px; font-size: 13px;">
                    <span id="detailDescription"></span>
                </div>
                
                <div class="row">
                    <div class="col-md-6">
                        <div style="border: 1px solid #e9ecef; border-radius: 6px; padding: 12px; margin-bottom: 10px;">
                            <h6 style="color: #495057; font-weight: 600; margin-bottom: 8px; font-size: 13px;">
                                <i class="fas fa-info-circle"></i> Informasi Dokumen:
                            </h6>
                            <div id="documentInfo"></div>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div style="border: 1px solid #e9ecef; border-radius: 6px; padding: 12px; margin-bottom: 10px;">
                            <h6 style="color: #495057; font-weight: 600; margin-bottom: 8px; font-size: 13px;">
                                <i class="fas fa-file-alt"></i> Data Pemohon:
                            </h6>
                            <div id="pemohonInfo"></div>
                        </div>
                    </div>
                </div>
                
                <div class="text-center" style="margin: 15px 0;">
                    <i class="fas fa-file-contract" style="font-size: 36px; color: #28a745; margin-bottom: 8px;"></i>
                    <div style="font-size: 14px; font-weight: 600; color: #2c3e50; margin-bottom: 3px;">
                        Konten Dokumen SP-MPT
                    </div>
                    <div style="font-size: 12px; color: #6c757d; margin-bottom: 10px;">
                        Preview dokumen resmi - Siap untuk diunduh
                    </div>
                    
                    <div style="background: #d4edda; border: 1px solid #c3e6cb; color: #155724; padding: 6px 12px; border-radius: 15px; font-size: 11px; font-weight: 500; display: inline-block;">
                        <i class="fas fa-check-circle"></i> Dokumen Valid & Terverifikasi
                    </div>
                </div>
            </div>
            
            <div class="modal-footer justify-content-center">
                <button type="button" class="btn btn-info btn-sm" style="border-radius: 15px; padding: 6px 15px;" onclick="printDocument()">
                    <i class="fas fa-print"></i> Cetak
                </button>
                <button type="button" class="btn btn-success btn-sm" style="border-radius: 15px; padding: 6px 15px;" onclick="downloadDocument()">
                    <i class="fas fa-download"></i> Unduh PDF
                </button>
                <button type="button" class="btn btn-secondary btn-sm" style="border-radius: 15px; padding: 6px 15px;" data-dismiss="modal">
                    <i class="fas fa-times"></i> Tutup
                </button>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>

function confirmDelete(itemName, deleteUrl) {
    $('#deleteItemName').text(itemName);
    $('#deleteForm').attr('action', deleteUrl);
    $('#deleteModal').modal('show');
}

// Initialize tooltips
$(function () {
    $('[data-toggle="tooltip"]').tooltip();
});

// Auto submit form on filter change
document.querySelectorAll('select[name="year"], select[name="status"]').forEach(function(element) {
    element.addEventListener('change', function() {
        document.getElementById('filterForm').submit();
    });
});

// Update status permohonan
$('.update-status').on('click', function() {
    const id = $(this).data('id');
    const status = $(this).data('status');
    const currentRow = $(this).closest('tr');
    const currentStatusBadge = currentRow.find('td:nth-child(4) .badge').text().trim();
    
    const statusText = status === 'approved' ? 'Selesai' : 'Belum Selesai';
    
    if ((status === 'approved' && currentStatusBadge.includes('Selesai')) || 
        (status === 'submitted' && currentStatusBadge.includes('Belum Selesai'))) {
        Swal.fire({
            icon: 'info',
            title: 'Informasi',
            text: 'Status sudah ' + statusText.toLowerCase() + '!',
            confirmButtonText: 'OK',
            confirmButtonColor: '#1cc88a',
        });
        return;
    }

    Swal.fire({
        title: 'Konfirmasi',
        text: 'Apakah Anda yakin ingin mengubah status permohonan menjadi ' + statusText + '?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#1cc88a',
        cancelButtonColor: '#e74a3b',
        confirmButtonText: 'Ya',
        cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: '{{ route("sp-sipt.updateStatus", ":id") }}'.replace(':id', id),
                method: 'POST',
                data: {
                    _token: '{{ csrf_token() }}',
                    status: status
                },
                success: function(response) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Sukses!',
                        text: 'Status permohonan berhasil diperbarui.',
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#1cc88a',
                    }).then(() => {
                        location.reload();
                    });
                },
                error: function(xhr) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: 'Gagal memperbarui status permohonan.',
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#e74a3b',
                    });
                }
            });
        }
    });
});

// Search on enter key
document.querySelector('input[name="search"]').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        e.preventDefault();
        document.getElementById('filterForm').submit();
    }
});

// Success/Error Messages
@if(session('success'))
    $(document).ready(function() {
        Swal.fire({
            icon: 'success',
            title: 'Sukses!',
            text: '{{ session('success') }}',
            confirmButtonText: 'OK',
            confirmButtonColor: '#1cc88a',
        });
    });
@endif

@if(session('error'))
    $(document).ready(function() {
        Swal.fire({
            icon: 'error',
            title: 'Error!',
            text: '{{ session('error') }}',
            confirmButtonText: 'OK',
            confirmButtonColor: '#e74a3b',
        });
    });
@endif

// DIPERBAIKI: View detail modal dengan proper loading management
$('.view-detail').on('click', function(e) {
    e.preventDefault();
    
    const id = $(this).data('id');
    const button = $(this);
    
    console.log('Loading detail for ID:', id); // Debug log
    
    // Disable button dan show loading
    button.prop('disabled', true);
    
    // Show modal dengan loading
    $('#detailModal').modal('show');
    $('#detailModal').removeAttr('aria-hidden');
    
    // Set loading content
    const loadingHtml = `
        <div class="text-center p-5">
            <div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;">
                <span class="sr-only">Loading...</span>
            </div>
            <div class="mt-3">
                <h6 class="text-muted">Memuat data...</h6>
                <small class="text-muted">Mohon tunggu sebentar</small>
            </div>
        </div>
    `;
    $('#detailModal .modal-body').html(loadingHtml);
    
    // Set timeout untuk menghindari loading stuck
    const loadingTimeout = setTimeout(() => {
        showError('Timeout loading data. Silakan coba lagi.');
        button.prop('disabled', false);
    }, 15000); // 15 detik timeout
    
    // Fetch data via AJAX
    $.ajax({
        url: `/sp-sipt/${id}/detail`,
        method: 'GET',
        timeout: 10000, // 10 detik timeout untuk AJAX
        success: function(response) {
            console.log('AJAX Success:', response); // Debug log
            clearTimeout(loadingTimeout);
            
            // Validasi response
            if (response && response.success && response.data) {
                console.log('Populating modal with data'); // Debug log
                populateDetailModal(response.data);
            } else {
                console.log('Invalid response format:', response); // Debug log
                showError('Format data tidak valid: ' + (response?.message || 'Data kosong'));
            }
        },
        error: function(xhr, status, error) {
            console.log('AJAX Error:', status, error, xhr); // Debug log
            clearTimeout(loadingTimeout);
            
            let message = 'Terjadi kesalahan saat memuat data.';
            
            if (status === 'timeout') {
                message = 'Koneksi timeout. Silakan coba lagi.';
            } else if (xhr.status === 404) {
                message = 'Data tidak ditemukan.';
            } else if (xhr.status === 500) {
                message = 'Terjadi kesalahan server.';
            } else if (xhr.responseJSON && xhr.responseJSON.message) {
                message = xhr.responseJSON.message;
            } else if (error) {
                message = 'Error: ' + error;
            }
            
            showError(message);
        },
        complete: function() {
            console.log('AJAX Complete'); // Debug log
            button.prop('disabled', false);
        }
    });
});

// DIPERBAIKI: Populate detail modal dengan proper content
function populateDetailModal(data) {
    try {
        console.log('Starting to populate modal with:', data); // Debug log
        
        // Clear loading state terlebih dahulu
        $('#detailModal .modal-body').empty();
        
        // Validasi data
        if (!data || !data.pemohon) {
            throw new Error('Data pemohon tidak tersedia');
        }
        
        // Set modal title
        const titleText = `Surat Pernyataan Melepaskan Penguasaan Tanah - ${data.pemohon.nama} (${data.pemohon.nik})`;
        $('#detailModalTitle').text(titleText);
        $('#detailModalSubtitle').text(`No. BA: ${data.nomor_ba || 'Belum digenerate'}`);
        
        // Create main content
        const modalContent = `
            <div style="background: #e8f5e8; border-left: 4px solid #28a745; padding: 12px; margin-bottom: 20px; font-size: 14px; border-radius: 0 4px 4px 0;">
                <i class="fas fa-info-circle text-success"></i>
                Dokumen Surat Pernyataan Melepaskan Penguasaan Tanah - ${data.pemohon.nama} (${data.pemohon.nik}) untuk keperluan administrasi pertanahan.
            </div>
            
            <div class="row">
                <div class="col-md-6">
                    <div class="card border-0 shadow-sm mb-3">
                        <div class="card-header bg-primary text-white py-2">
                            <h6 class="mb-0"><i class="fas fa-info-circle"></i> Informasi Dokumen</h6>
                        </div>
                        <div class="card-body" id="documentInfo">
                            <!-- Will be populated -->
                        </div>
                    </div>
                </div>
                
                <div class="col-md-6">
                    <div class="card border-0 shadow-sm mb-3">
                        <div class="card-header bg-success text-white py-2">
                            <h6 class="mb-0"><i class="fas fa-user"></i> Data Pemohon</h6>
                        </div>
                        <div class="card-body" id="pemohonInfo">
                            <!-- Will be populated -->
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="text-center py-4">
                <div class="mb-3">
                    <i class="fas fa-file-contract text-success" style="font-size: 48px;"></i>
                </div>
                <h5 class="text-dark mb-2">Konten Dokumen SP-MPT</h5>
                <p class="text-muted mb-3">Preview dokumen resmi - Siap untuk diunduh</p>
                <div class="badge badge-success p-2">
                    <i class="fas fa-check-circle"></i> Dokumen Valid & Terverifikasi
                </div>
            </div>
        `;
        
        // Set content ke modal
        $('#detailModal .modal-body').html(modalContent);
        
        // Populate document info
        const documentInfoHtml = `
            <div class="row mb-2">
                <div class="col-5 text-muted small">Nama Dokumen:</div>
                <div class="col-7 font-weight-bold small">SP-MPT ${data.pemohon.nama}</div>
            </div>
            <div class="row mb-2">
                <div class="col-5 text-muted small">Nomor BA:</div>
                <div class="col-7 font-weight-bold small">${data.nomor_ba || 'Belum digenerate'}</div>
            </div>
            <div class="row mb-2">
                <div class="col-5 text-muted small">Tanggal:</div>
                <div class="col-7 font-weight-bold small">${data.created_at || 'Tidak tersedia'}</div>
            </div>
            <div class="row mb-2">
                <div class="col-5 text-muted small">Status:</div>
                <div class="col-7">
                    <span class="badge badge-sm ${getBadgeClass(data.status_class)}">${data.status_label || 'Unknown'}</span>
                </div>
            </div>
            <div class="row mb-2">
                <div class="col-5 text-muted small">Koordinat:</div>
                <div class="col-7 font-weight-bold small">${data.coordinates_count || 0} titik</div>
            </div>
            <div class="row mb-2">
                <div class="col-5 text-muted small">Luas Terukur:</div>
                <div class="col-7 font-weight-bold small">${data.luas_terukur || 'Belum dihitung'}</div>
            </div>
        `;
        $('#documentInfo').html(documentInfoHtml);
        
        // Populate pemohon info
        const pemohonInfoHtml = `
            <div class="row mb-2">
                <div class="col-4 text-muted small">Pemohon:</div>
                <div class="col-8 font-weight-bold small">${data.pemohon.nama || 'Tidak tersedia'}</div>
            </div>
            <div class="row mb-2">
                <div class="col-4 text-muted small">NIK:</div>
                <div class="col-8 font-weight-bold small">${data.pemohon.nik || 'Tidak tersedia'}</div>
            </div>
            <div class="row mb-2">
                <div class="col-4 text-muted small">Alamat:</div>
                <div class="col-8 font-weight-bold small">${(data.pemohon.alamat || '').substring(0, 50)}${(data.pemohon.alamat || '').length > 50 ? '...' : ''}</div>
            </div>
            <div class="row mb-2">
                <div class="col-4 text-muted small">Lokasi:</div>
                <div class="col-8 font-weight-bold small">${(data.lokasi?.kampung || 'N/A')}, ${(data.lokasi?.kecamatan || 'N/A')}</div>
            </div>
            <div class="row mb-2">
                <div class="col-4 text-muted small">Terlapor:</div>
                <div class="col-8 font-weight-bold small">${data.terlapor?.nama || 'Tidak tersedia'}</div>
            </div>
            <div class="row mb-2">
                <div class="col-4 text-muted small">Dibuat oleh:</div>
                <div class="col-8 font-weight-bold small">${data.created_by || 'Unknown'}</div>
            </div>
            <div class="row mb-2">
                <div class="col-4 text-muted small">Dokumen:</div>
                <div class="col-8 font-weight-bold small">${(data.dokumen || []).length} file</div>
            </div>
        `;
        $('#pemohonInfo').html(pemohonInfoHtml);
        
        // Store current data for actions
        window.currentSpSiptData = data;
        
        console.log('Modal populated successfully'); // Debug log
        
    } catch (error) {
        console.error('Error populating modal:', error); // Debug log
        showError('Gagal menampilkan data: ' + error.message);
    }
}

// DIPERBAIKI: Show error function
function showError(message) {
    const errorContent = `
        <div class="text-center py-5">
            <div class="mb-3">
                <i class="fas fa-exclamation-triangle text-danger" style="font-size: 48px;"></i>
            </div>
            <h5 class="text-danger mb-3">Terjadi Kesalahan</h5>
            <p class="text-muted mb-4">${message}</p>
            <button type="button" class="btn btn-outline-primary" onclick="location.reload()">
                <i class="fas fa-refresh"></i> Muat Ulang Halaman
            </button>
        </div>
    `;
    
    $('#detailModal .modal-body').html(errorContent);
}

// Helper function untuk badge class
function getBadgeClass(statusClass) {
    const classMap = {
        'text-success': 'badge-success',
        'text-danger': 'badge-danger',
        'text-warning': 'badge-warning',
        'text-info': 'badge-info',
        'text-secondary': 'badge-secondary'
    };
    return classMap[statusClass] || 'badge-secondary';
}

// Print document function
function printDocument() {
    if (window.currentSpSiptData && window.currentSpSiptData.urls) {
        window.open(window.currentSpSiptData.urls.print, '_blank');
    } else {
        Swal.fire({
            icon: 'error',
            title: 'Error!',
            text: 'Data dokumen tidak tersedia untuk dicetak.',
        });
    }
}

// Download document function
function downloadDocument() {
    if (window.currentSpSiptData && window.currentSpSiptData.urls) {
        // Show loading
        Swal.fire({
            title: 'Mengunduh...',
            text: 'Mohon tunggu, dokumen sedang diproses.',
            allowOutsideClick: false,
            showConfirmButton: false,
            willOpen: () => {
                Swal.showLoading();
            }
        });
        
        // Start download
        window.location.href = window.currentSpSiptData.urls.download;
        
        // Close loading after delay
        setTimeout(() => {
            Swal.close();
        }, 2000);
    } else {
        Swal.fire({
            icon: 'error',
            title: 'Error!',
            text: 'Data dokumen tidak tersedia untuk diunduh.',
        });
    }
}

// Send email function dengan SweetAlert2
function sendEmail() {
    if (!window.currentSpSiptData) {
        Swal.fire({
            icon: 'error',
            title: 'Error!',
            text: 'Data dokumen tidak tersedia.',
        });
        return;
    }
    
    Swal.fire({
        title: 'Kirim Email',
        html: `
            <div class="form-group text-left">
                <label for="email">Email Tujuan:</label>
                <input type="email" id="email" class="form-control" placeholder="contoh@email.com" required>
            </div>
            <div class="form-group text-left">
                <label for="subject">Subject:</label>
                <input type="text" id="subject" class="form-control" value="Dokumen SP-MPT ${window.currentSpSiptData.nomor_ba}">
            </div>
            <div class="form-group text-left">
                <label for="message">Pesan:</label>
                <textarea id="message" class="form-control" rows="3">Terlampir dokumen Surat Pernyataan Melepaskan Penguasaan Tanah.</textarea>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Kirim Email',
        cancelButtonText: 'Batal',
        confirmButtonColor: '#28a745',
        preConfirm: () => {
            const email = document.getElementById('email').value;
            const subject = document.getElementById('subject').value;
            const message = document.getElementById('message').value;
            
            if (!email) {
                Swal.showValidationMessage('Email harus diisi');
                return false;
            }
            
            if (!isValidEmail(email)) {
                Swal.showValidationMessage('Format email tidak valid');
                return false;
            }
            
            return { email, subject, message };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const { email, subject, message } = result.value;
            
            // Show loading
            Swal.fire({
                title: 'Mengirim Email...',
                allowOutsideClick: false,
                showConfirmButton: false,
                willOpen: () => {
                    Swal.showLoading();
                }
            });
            
            $.ajax({
                url: `/sp-sipt/${window.currentSpSiptData.id}/send-email`,
                method: 'POST',
                data: {
                    email: email,
                    subject: subject,
                    message: message,
                    _token: $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Berhasil!',
                            text: response.message,
                            confirmButtonColor: '#28a745'
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Gagal!',
                            text: response.message,
                        });
                    }
                },
                error: function(xhr) {
                    let message = 'Gagal mengirim email.';
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        message = xhr.responseJSON.message;
                    }
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: message,
                    });
                }
            });
        }
    });
}

// Update status function (if needed)
function updateStatusInModal(newStatus) {
    if (!window.currentSpSiptData) return;
    
    const statusText = getStatusText(newStatus);
    
    Swal.fire({
        title: 'Konfirmasi',
        text: `Ubah status menjadi ${statusText}?`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#28a745',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Ya, Ubah',
        cancelButtonText: 'Batal',
        input: 'textarea',
        inputPlaceholder: 'Catatan (opsional)...'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: `/sp-sipt/${window.currentSpSiptData.id}/update-status-ajax`,
                method: 'POST',
                data: {
                    status: newStatus,
                    catatan: result.value,
                    _token: $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Berhasil!',
                            text: response.message,
                            confirmButtonColor: '#28a745'
                        }).then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Gagal!',
                            text: response.message,
                        });
                    }
                },
                error: function(xhr) {
                    let message = 'Gagal mengubah status.';
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        message = xhr.responseJSON.message;
                    }
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: message,
                    });
                }
            });
        }
    });
}

// Helper functions
function isValidEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

function getStatusText(status) {
    switch(status) {
        case 'draft': return 'Draft';
        case 'submitted': return 'Belum Selesai';
        case 'in_review': return 'Sedang Ditinjau';
        case 'approved': return 'Terverifikasi';
        case 'rejected': return 'Ditolak';
        default: return 'Unknown';
    }
}

// Modal event handlers untuk cleanup
$('#detailModal').on('hidden.bs.modal', function () {
    // Reset modal content dan data
    $(this).find('.modal-body').empty();
    $(this).find('#detailModalTitle').text('');
    $(this).find('#detailModalSubtitle').text('');
    window.currentSpSiptData = null;
    
    console.log('Modal closed and cleaned up'); // Debug log
});

// Initialize CSRF token for AJAX
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

// Document ready
$(document).ready(function() {
    console.log('SP-MPT scripts loaded successfully'); // Debug log
});

</script>
@endpush

@push('styles')
<style>
.border-left-primary {
    border-left: 0.25rem solid #4e73df !important;
}
.border-left-success {
    border-left: 0.25rem solid #1cc88a !important;
}
.border-left-info {
    border-left: 0.25rem solid #36b9cc !important;
}
.border-left-warning {
    border-left: 0.25rem solid #f6c23e !important;
}
.border-left-secondary {
    border-left: 0.25rem solid #858796 !important;
}
.border-left-danger {
    border-left: 0.25rem solid #e74a3b !important;
}

.table-hover tbody tr:hover {
    background-color: rgba(0,0,0,.02);
}

.btn-group .btn {
    margin: 0 1px;
}

.card {
    box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15) !important;
}

.text-gray-800 {
    color: #5a5c69 !important;
}

.text-gray-300 {
    color: #dddfeb !important;
}

@media print {
    .btn, .card-footer, #filterForm, .card-header .btn {
        display: none !important;
    }
}
</style>
@endpush
