@extends('admin-layouts.master')

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

@section('content')
<style>
.nav-tabs .nav-link {
    color: #495057 !important;
}
.nav-tabs .nav-link.active {
    color: #000 !important;
    background-color: #fff !important;
    border: 1px solid #dee2e6;
    border-bottom-color: transparent;
    font-weight: 600;
}
</style>
<div class="row">
    <div class="col-12">
        <!-- Header dengan styling hijau modern seperti gambar -->
        <div class="card shadow-sm mb-4 mt-3" style="background: linear-gradient(135deg, #00c851, #007e33); color: white;">
            <div class="card-body py-3">
                <div>
                    <h5 class="mb-0 font-weight-bold">PENERBITAN SP-MPT</h5>
                    <small>Surat Pernyataan Melepaskan Penguasaan Tanah</small>
                </div>
            </div>
        </div>
        <!-- Filter Section -->
        <div class="card shadow-sm mb-3">
            <div class="card-body py-3">
                <form method="GET" action="{{ route('penerbitan-spmpt.index') }}" class="row align-items-end g-2">
                    <div class="col-md-2">
                        <label for="tahun_spmpt" class="form-label small font-weight-bold mb-1">Tahun SP-MPT:</label>
                        <select class="form-control form-control-sm" id="tahun_spmpt" name="tahun_spmpt">
                            <option value="">Semua</option>
                            @foreach($years as $year)
                                <option value="{{ $year }}" {{ request('tahun_spmpt') == $year ? 'selected' : '' }}>
                                    {{ $year }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="cari_berdasarkan" class="form-label small font-weight-bold mb-1">Cari Berdasarkan:</label>
                        <select class="form-control form-control-sm" id="cari_berdasarkan" name="cari_berdasarkan">
                            <option value="">Pilih...</option>
                            <option value="no_registrasi" {{ request('cari_berdasarkan') == 'no_registrasi' ? 'selected' : '' }}>No. Registrasi</option>
                            <option value="nama_pemohon" {{ request('cari_berdasarkan') == 'nama_pemohon' ? 'selected' : '' }}>Nama Pemohon</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label for="search" class="form-label small font-weight-bold mb-1">Kata Kunci:</label>
                        <input type="text" class="form-control form-control-sm"
                               id="search" name="search"
                               placeholder="Masukkan kata kunci pencarian"
                               value="{{ request('search') }}">
                    </div>
                    <div class="col-md-auto">
                        <button type="submit" class="btn btn-primary btn-sm px-3" style="background-color: #4285f4; border-color: #4285f4;">
                            <i class="fas fa-search"></i> Find
                        </button>
                    </div>
                    <div class="col-md-auto">
                        <a href="{{ route('penerbitan-spmpt.index') }}" class="btn btn-secondary btn-sm px-3">
                            <i class="fas fa-times"></i> Reset
                        </a>
                    </div>
                </form>
            </div>
        </div>

        <!-- Data Table -->
        <div class="card shadow-sm">
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0 table-bordered">
                        <thead style="background-color: #00c851; color: white;">
                            <tr>
                                <th class="text-center align-middle" style="width: 50px;">NO</th>
                                <th class="text-center align-middle" style="width: 80px;">NO_REG</th>
                                <th class="text-center align-middle" style="width: 80px;">THN_REG</th>
                                <th class="text-center align-middle" style="width: 200px;">PIHAK PERTAMA</th>
                                <th class="text-center align-middle" style="width: 200px;">PIHAK KEDUA</th>
                                <th class="text-center align-middle" style="width: 100px;">TGL_SP-MPT</th>
                                <th class="text-center align-middle" style="width: 80px;">NO_SP-MPT</th>
                                <th class="text-center align-middle" style="width: 80px;">CETAK</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($applications as $index => $app)
                            <tr class="{{ $loop->iteration % 2 == 0 ? 'bg-light-yellow' : 'bg-white' }}">
                                <td class="text-center align-middle">{{ $applications->firstItem() + $index }}</td>
                                <td class="text-center align-middle">
                                    <span class="font-weight-bold">
                                        {{ str_pad($loop->iteration, 4, '0', STR_PAD_LEFT) }}
                                    </span>
                                </td>
                                <td class="text-center align-middle">
                                    {{ $app->created_at->format('Y') }}
                                </td>
                                <td class="align-middle">
                                    <strong>{{ strtoupper($app->pemohon_nama) }}</strong>
                                </td>
                                <td class="align-middle">
                                    {{ strtoupper($app->terlapor_nama) }}
                                </td>
                                <td class="text-center align-middle">
                                    {{ $app->created_at->format('d M Y') }}
                                </td>
                                <td class="text-center align-middle">
                                    <span class="font-weight-bold">
                                        {{ str_pad($loop->iteration, 4, '0', STR_PAD_LEFT) }}
                                    </span>
                                </td>
                                <td class="text-center align-middle">
                                    <div class="btn-group" role="group">
                                        <button type="button"
                                                class="btn btn-sm text-white"
                                                style="background-color: #00c851; border-color: #00c851;"
                                                data-toggle="tooltip"
                                                title="Cetak SP-MPT"
                                                onclick="printSpmpt('{{ $app->id }}')">
                                            <i class="fas fa-print"></i>
                                        </button>
                                        {{-- <button type="button"
                                                class="btn btn-sm text-white"
                                                style="background-color: #33b5e5; border-color: #33b5e5;"
                                                data-toggle="tooltip"
                                                title="Lihat Detail"
                                                onclick="showDetail('{{ $app->id }}')">
                                            <i class="fas fa-eye"></i>
                                        </button> --}}
                                         <a href="#"
                                            class="btn btn-sm btn-outline-primary view-detail"
                                            data-toggle="tooltip" title="Lihat Detail"
                                            data-id="{{ $app->id }}"
                                            data-name="{{ $app->pemohon_nama }}"
                                            data-nik="{{ $app->pemohon_nik }}"
                                            data-nomor-ba="{{ $app->nomor_surat }}"
                                            data-status="{{ $app->status }}">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            @empty
                            <tr>
                                <td colspan="8" class="text-center py-5">
                                    <div class="text-muted">
                                        <i class="fas fa-folder-open fa-3x mb-3"></i>
                                        <h5>Tidak ada data</h5>
                                        <p>Belum ada data SP-MPT yang siap untuk diterbitkan</p>
                                    </div>
                                </td>
                            </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>

                @if($applications->hasPages())
                <div class="card-footer bg-white border-top-0">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="showing-info">
                            <small class="text-muted">
                                Menampilkan {{ $applications->firstItem() }} - {{ $applications->lastItem() }}
                                dari {{ $applications->total() }} data
                            </small>
                        </div>
                        {{ $applications->links() }}
                    </div>
                </div>
                @endif
            </div>
        </div>
    </div>
</div>

<!-- Detail Modal -->
<!-- Detail Modal dengan Tabs -->
<div class="modal fade" id="detailModal" tabindex="-1" role="dialog" aria-labelledby="detailModalTitle">
    <div class="modal-dialog modal-xl" 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" aria-label="Tutup detail">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>

            <div class="modal-body p-0" style="max-height: 80vh; overflow: hidden;">
                <!-- Content akan dimuat via JavaScript -->
            </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-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>
// Initialize tooltips
$(function () {
    $('[data-toggle="tooltip"]').tooltip();
});

// function showDetail(id) {
//     $.ajax({
//         url: '{{ route("penerbitan-spmpt.show", ":id") }}'.replace(':id', id),
//         method: 'GET',
//         success: function(response) {
//             let html = `
//                 <div class="row">
//                     <div class="col-md-6">
//                         <h6 class="font-weight-bold mb-3">Data Pemohon (Pihak Pertama)</h6>
//                         <table class="table table-sm">
//                             <tr>
//                                 <td width="40%">Nomor Surat</td>
//                                 <td width="5%">:</td>
//                                 <td>${response.nomor_surat}</td>
//                             </tr>
//                             <tr>
//                                 <td>Nama</td>
//                                 <td>:</td>
//                                 <td>${response.pemohon_nama}</td>
//                             </tr>
//                             <tr>
//                                 <td>NIK</td>
//                                 <td>:</td>
//                                 <td>${response.pemohon_nik}</td>
//                             </tr>
//                         </table>
//                     </div>
//                     <div class="col-md-6">
//                         <h6 class="font-weight-bold mb-3">Data Terlapor (Pihak Kedua)</h6>
//                         <table class="table table-sm">
//                             <tr>
//                                 <td width="40%">Nama</td>
//                                 <td width="5%">:</td>
//                                 <td>${response.terlapor_nama}</td>
//                             </tr>
//                             <tr>
//                                 <td>Status</td>
//                                 <td>:</td>
//                                 <td><span class="badge badge-success">${response.status.toUpperCase()}</span></td>
//                             </tr>
//                             <tr>
//                                 <td>Tanggal</td>
//                                 <td>:</td>
//                                 <td>${response.created_at}</td>
//                             </tr>
//                         </table>
//                     </div>
//                 </div>
//             `;
//             $('#detailContent').html(html);
//             $('#detailModal').modal('show');
//         },
//         error: function(xhr) {
//             Swal.fire({
//                 icon: 'error',
//                 title: 'Error!',
//                 text: 'Gagal memuat detail data.',
//                 confirmButtonColor: '#e74a3b',
//             });
//         }
//     });
// }

function printSpmpt(id) {
    Swal.fire({
        title: 'Cetak SP-MPT',
        text: 'Apakah Anda yakin ingin mencetak SP-MPT ini?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#00c851',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Ya, Cetak!',
        cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.isConfirmed) {
            window.open('{{ route("penerbitan-spmpt.print", ":id") }}'.replace(':id', id), '_blank');
        }
    });
}
// 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);

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

    // Fetch data via AJAX
    $.ajax({
        url: `/sp-sipt/${id}/detail`,
        method: 'GET',
        timeout: 10000,
        success: function(response) {
            console.log('AJAX Success:', response);
            clearTimeout(loadingTimeout);

            if (response && response.success && response.data) {
                console.log('Populating modal with data');
                populateDetailModal(response.data);
            } else {
                console.log('Invalid response format:', response);
                showError('Format data tidak valid: ' + (response?.message || 'Data kosong'));
            }
        },
        error: function(xhr, status, error) {
            console.log('AJAX Error:', status, error, xhr);
            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');
            button.prop('disabled', false);
        }
    });
});

// Populate detail modal dengan tabs untuk detail dan preview
function populateDetailModal(data) {
    try {
        console.log('Starting to populate modal with:', data);

        // 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 tabbed content with detail and preview
        const modalContent = `
            <!-- Nav tabs -->
            <ul class="nav nav-tabs" id="detailTabs" role="tablist">
                <li class="nav-item">
                    <a class="nav-link active" id="detail-tab" data-toggle="tab" href="#detail" role="tab">
                        <i class="fas fa-info-circle"></i> Detail Dokumen
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" id="preview-tab" data-toggle="tab" href="#preview" role="tab">
                        <i class="fas fa-eye"></i> Print Preview
                    </a>
                </li>
            </ul>

            <!-- Tab panes -->
            <div class="tab-content" id="detailTabContent">
                <!-- Detail Tab -->
                <div class="tab-pane fade show active" id="detail" role="tabpanel">
                    <div class="p-3">
                        <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>
                    </div>
                </div>

                <!-- Preview Tab -->
                <div class="tab-pane fade" id="preview" role="tabpanel">
                    <div class="p-2">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h6 class="mb-0">Print Preview - SP-MPT</h6>
                            <div class="btn-group btn-group-sm">
                                <button type="button" class="btn btn-outline-secondary" onclick="zoomOut()">
                                    <i class="fas fa-search-minus"></i>
                                </button>
                                <button type="button" class="btn btn-outline-secondary" onclick="resetZoom()">
                                    <span id="zoomLevel">100%</span>
                                </button>
                                <button type="button" class="btn btn-outline-secondary" onclick="zoomIn()">
                                    <i class="fas fa-search-plus"></i>
                                </button>
                            </div>
                        </div>
                        <div id="printPreviewContainer" style="max-height: 500px; overflow-y: auto; border: 1px solid #ddd; background: #f8f9fa;">
                            <div id="printPreviewContent" style="transform-origin: top left; transition: transform 0.3s;">
                                <!-- Print preview akan dimuat di sini -->
                                <div class="text-center p-4">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="sr-only">Loading preview...</span>
                                    </div>
                                    <p class="mt-2 text-muted">Memuat preview...</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;

        // Set content ke modal
        $('#detailModal .modal-body').html(modalContent);

        // Populate document info
        populateDocumentInfo(data);
        populatePemohonInfo(data);

        // Store current data for actions
        window.currentSpSiptData = data;

        console.log('Modal populated successfully');

    } catch (error) {
        console.error('Error populating modal:', error);
        showError('Gagal menampilkan data: ' + error.message);
    }
}

// Function untuk populate document info
function populateDocumentInfo(data) {
    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);
}

// Function untuk populate pemohon info
function populatePemohonInfo(data) {
    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);
}

// Load print preview when preview tab is clicked
$(document).on('shown.bs.tab', '#preview-tab', function () {
    if (!window.currentSpSiptData) return;

    console.log('Loading print preview...');

    // Show loading in preview
    $('#printPreviewContent').html(`
        <div class="text-center p-4">
            <div class="spinner-border text-primary" role="status">
                <span class="sr-only">Loading preview...</span>
            </div>
            <p class="mt-2 text-muted">Memuat preview...</p>
        </div>
    `);

    // Load print URL directly in iframe
    const printUrl = '{{ route("penerbitan-spmpt.print", ":id") }}'.replace(':id', window.currentSpSiptData.id);

    $('#printPreviewContent').html(`
        <iframe
            src="${printUrl}"
            style="width: 100%; height: 600px; border: none; background: white;"
            onload="this.style.display='block';">
        </iframe>
    `);
});

// Function untuk load simplified preview
function loadSimplifiedPreview() {
    const data = window.currentSpSiptData;
    const previewHtml = `
        <div style="background: white; padding: 20px; font-family: 'Times New Roman', serif; font-size: 12px; max-width: 800px; margin: 0 auto;">
            <!-- Cover Page Preview -->
            <div style="text-align: center; border: 3px double #000; padding: 40px; margin-bottom: 20px;">
                <div style="margin-bottom: 30px;">
                    <img src="/images/logo-berau.png" alt="Logo" style="width: 120px; height: auto;">
                </div>
                <h2 style="font-size: 18pt; font-weight: bold; line-height: 1.5;">
                    SURAT PERNYATAAN<br>
                    MELEPASKAN PENGUASAAN ATAS TANAH
                </h2>
                <p style="margin-top: 30px;">
                    <strong>Nomor : ${data.nomor_ba || '.....................................................'}</strong><br>
                    <strong>Tahun : ${new Date().getFullYear()}</strong>
                </p>
            </div>

            <!-- Document Info Preview -->
            <div style="border: 1px solid #ddd; padding: 15px; margin-bottom: 20px;">
                <h4 style="text-align: center; text-decoration: underline; margin-bottom: 15px;">
                    SURAT PERNYATAAN MELEPASKAN PENGUASAAN ATAS TANAH
                </h4>
                <p style="text-align: center; margin-bottom: 20px;">
                    Nomor : ${data.nomor_ba || '.........................................................................'}
                </p>

                <p><strong>PIHAK PERTAMA:</strong></p>
                <table style="width: 100%; margin-bottom: 15px;">
                    <tr><td style="width: 150px;">Nama</td><td>: ${data.pemohon.nama}</td></tr>
                    <tr><td>NIK</td><td>: ${data.pemohon.nik}</td></tr>
                    <tr><td>Alamat</td><td>: ${data.pemohon.alamat || 'Tidak tersedia'}</td></tr>
                </table>

                <p><strong>PIHAK KEDUA:</strong></p>
                <table style="width: 100%; margin-bottom: 15px;">
                    <tr><td style="width: 150px;">Nama</td><td>: ${data.terlapor.nama || 'Tidak tersedia'}</td></tr>
                    <tr><td>NIK</td><td>: ${data.terlapor.nik || 'Tidak tersedia'}</td></tr>
                    <tr><td>Alamat</td><td>: ${data.terlapor.alamat || 'Tidak tersedia'}</td></tr>
                </table>

                <p><strong>DATA TANAH:</strong></p>
                <table style="width: 100%;">
                    <tr><td style="width: 150px;">Lokasi</td><td>: ${data.lokasi.kampung}, ${data.lokasi.kecamatan}</td></tr>
                    <tr><td>Luas Terukur</td><td>: ${data.luas_terukur || 'Belum dihitung'} M²</td></tr>
                    <tr><td>Koordinat</td><td>: ${data.coordinates_count} titik</td></tr>
                </table>
            </div>

            <!-- Map Preview -->
            <div style="border: 1px solid #ddd; padding: 10px; text-align: center;">
                <h5>SKET/GAMBAR KASAR TANAH</h5>
                <div style="border: 1px solid #ccc; height: 200px; background: #f8f9fa; display: flex; align-items: center; justify-content: center; margin: 10px 0;">
                    <p style="color: #666;">Preview Peta Tanah</p>
                </div>
                <div style="display: flex; justify-content: space-between; margin-top: 10px;">
                    <div style="flex: 1;">
                        <p><strong>Batas Tanah:</strong></p>
                        <p>Utara: ${data.lokasi?.batas_utara || 'Tidak tersedia'}</p>
                        <p>Timur: ${data.lokasi?.batas_timur || 'Tidak tersedia'}</p>
                        <p>Selatan: ${data.lokasi?.batas_selatan || 'Tidak tersedia'}</p>
                        <p>Barat: ${data.lokasi?.batas_barat || 'Tidak tersedia'}</p>
                    </div>
                    <div style="flex: 1; text-align: center;">
                        <p><strong>Yang membuat Sket/Gambar Tanah</strong></p>
                        <div style="height: 60px;"></div>
                        <p style="text-decoration: underline;">______________________</p>
                        <p>NIP. ...................................</p>
                    </div>
                </div>
            </div>

            <div style="text-align: center; margin-top: 20px; color: #666;">
                <small>* Ini adalah preview sederhana. Untuk melihat format lengkap, gunakan tombol Print atau Download PDF.</small>
            </div>
        </div>
    `;

    $('#printPreviewContent').html(previewHtml);
}

// Zoom functions for preview
let currentZoom = 1;

function zoomIn() {
    currentZoom = Math.min(currentZoom + 0.1, 2);
    updateZoom();
}

function zoomOut() {
    currentZoom = Math.max(currentZoom - 0.1, 0.5);
    updateZoom();
}

function resetZoom() {
    currentZoom = 1;
    updateZoom();
}

function updateZoom() {
    $('#printPreviewContent').css('transform', `scale(${currentZoom})`);
    $('#zoomLevel').text(Math.round(currentZoom * 100) + '%');
}

// Rest of the existing functions...
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);
}

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

function printDocument() {
    if (window.currentSpSiptData && window.currentSpSiptData.id) {
        const printUrl = '{{ route("penerbitan-spmpt.print", ":id") }}'.replace(':id', window.currentSpSiptData.id);
        window.open(printUrl, '_blank');
    } else {
        Swal.fire({
            icon: 'error',
            title: 'Error!',
            text: 'Data dokumen tidak tersedia untuk dicetak.',
        });
    }
}

function downloadDocument() {
    if (window.currentSpSiptData && window.currentSpSiptData.urls) {
        Swal.fire({
            title: 'Mengunduh...',
            text: 'Mohon tunggu, dokumen sedang diproses.',
            allowOutsideClick: false,
            showConfirmButton: false,
            willOpen: () => {
                Swal.showLoading();
            }
        });

        window.location.href = window.currentSpSiptData.urls.download;

        setTimeout(() => {
            Swal.close();
        }, 2000);
    } else {
        Swal.fire({
            icon: 'error',
            title: 'Error!',
            text: 'Data dokumen tidak tersedia untuk diunduh.',
        });
    }
}

// Send email function
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;

            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
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;
    currentZoom = 1; // Reset zoom level

    console.log('Modal closed and cleaned up');
});

// 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 with preview loaded successfully');
});

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

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

@push('styles')
<style>
.card {
    border: none;
}

.table {
    margin-bottom: 0;
}

.table th {
    font-size: 11px;
    font-weight: 700;
    padding: 10px 8px;
    white-space: nowrap;
}

.table td {
    font-size: 12px;
    padding: 8px;
    vertical-align: middle;
}

.table-bordered {
    border: 1px solid #dee2e6;
}

.table-bordered th,
.table-bordered td {
    border: 1px solid #dee2e6;
}

/* Alternating row colors seperti di gambar */
.bg-light-yellow {
    background-color: #fffef0 !important;
}

.bg-white {
    background-color: #ffffff !important;
}

.table-hover tbody tr:hover {
    background-color: rgba(0, 200, 81, 0.05) !important;
}

.btn-group .btn {
    margin: 0 2px;
    padding: 4px 10px;
}

.badge {
    font-size: 11px;
    font-weight: 600;
    padding: 4px 8px;
}

.form-label {
    color: #495057;
    font-size: 13px;
}

.btn-sm {
    font-size: 12px;
}

/* Header gradient hijau seperti gambar */
.card-body h5 {
    font-size: 16px;
    letter-spacing: 0.5px;
}

/* Custom scrollbar untuk table */
.table-responsive::-webkit-scrollbar {
    height: 8px;
}

.table-responsive::-webkit-scrollbar-track {
    background: #f1f1f1;
}

.table-responsive::-webkit-scrollbar-thumb {
    background: #00c851;
    border-radius: 4px;
}

/* Responsive */
@media (max-width: 768px) {
    .card-body {
        padding: 1rem 0.75rem;
    }

    .table th,
    .table td {
        padding: 6px 4px;
        font-size: 10px;
    }

    .btn-sm {
        padding: 0.2rem 0.4rem;
        font-size: 10px;
    }
}
</style>
@endpush
