@extends('admin-layouts.master')

@section('title', 'Penerbitan Cek SKPT')

@section('content')
<div class="row">
    <div class="col-12">
        <!-- Header dengan styling orange/modern -->
        <div class="card shadow-sm mb-4 mt-3" style="background: linear-gradient(135deg, #ff8a00, #e52e71); color: white;">
            <div class="card-body py-4">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h3 class="mb-1 font-weight-bold">PENERBITAN</h3>
                        <h4 class="mb-0">Cetak SKPT</h4>
                    </div>
                    <div class="d-none d-md-block">
                        <i class="fas fa-print fa-3x opacity-50"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filter Section -->
        <div class="card shadow-sm mb-4">
            <div class="card-body">
                <form method="GET" action="{{ route('penerbitan-skpt.index') }}" class="row align-items-end">
                    <div class="col-md-2">
                        <label for="tahun_skpt" class="form-label small font-weight-bold">Tahun SKPT:</label>
                        <select class="form-control form-control-sm" id="tahun_skpt" name="tahun_skpt">
                            <option value="">Semua</option>
                            @foreach($years as $year)
                                <option value="{{ $year }}" {{ request('tahun_skpt') == $year ? 'selected' : '' }}>
                                    {{ $year }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="cari_berdasarkan" class="form-label small font-weight-bold">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">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-1">
                        <button type="submit" class="btn btn-primary btn-sm px-3">
                            <i class="fas fa-search"></i> Find
                        </button>
                    </div>
                    <div class="col-md-1">
                        <a href="{{ route('penerbitan-skpt.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">
                        <thead style="background-color: #ff8a00; color: white;">
                            <tr>
                                <th class="text-center" style="width: 5%;">NO</th>
                                <th class="text-center" style="width: 8%;">NO_REG</th>
                                <th class="text-center" style="width: 8%;">THN_REG</th>
                                <th class="text-center" style="width: 20%;">NAMA PEMOHON</th>
                                <th class="text-center" style="width: 12%;">TGL_BA PENELITIAN</th>
                                <th class="text-center" style="width: 12%;">NO_BA PENELITIAN</th>
                                <th class="text-center" style="width: 10%;">TGL_SKPT</th>
                                <th class="text-center" style="width: 8%;">NO_SKPT</th>
                                <th class="text-center" style="width: 10%;">STATUS</th>
                                <th class="text-center" style="width: 7%;">ACTION</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($applications as $index => $app)
                            <tr class="{{ $loop->iteration % 2 == 0 ? 'bg-light' : '' }}">
                                <td class="text-center font-weight-bold">{{ $applications->firstItem() + $index }}</td>
                                <td class="text-center">
                                    <span class="font-weight-bold text-primary">
                                        {{$app->no_registrasi}}
                                    </span>
                                </td>
                                <td class="text-center">
                                    {{ $app->created_at->format('Y') }}
                                </td>
                                <td class="font-weight-bold text-center">
                                    {{ strtoupper($app->nama_pemohon) }}
                                </td>
                                <td class="text-center">
                                    {{ $app->dataPeninjauan->ba_tanggal ? $app->dataPeninjauan->ba_tanggal->format('d M Y') : '-' }}
                                </td>
                                <td class="text-center">
                                    {{ $app->dataPeninjauan->nomor_ba_penelitian ?? '-' }}
                                </td>
                                <td class="text-center">
                                    {{ $app->created_at->format('d M Y') }}
                                </td>
                                <td class="text-center">
                                    {{ explode('-', $app->no_registrasi)[2] ?? '' }}
                                </td>
                                <td class="text-center">
                                    @if($app->status_permohonan == 'SELESAI')
                                        <span class="badge badge-success px-2 py-1">SELESAI</span>
                                    @else
                                        <span class="badge badge-warning px-2 py-1">BELUM SELESAI</span>
                                    @endif
                                </td>
                                <td class="text-center">
                                    <div class="btn-group" role="group">
                                        {{-- <button type="button"
                                                class="btn btn-sm btn-info text-white"
                                                data-toggle="tooltip" title="Lihat Detail"
                                                onclick="showDetail('{{ $app->id }}')">
                                            <i class="fas fa-eye"></i>
                                        </button> --}}
                                        <button type="button"
                                                class="btn btn-sm btn-warning text-white"
                                                data-toggle="tooltip" title="Preview & Verifikasi"
                                                onclick="showPreviewModal('{{ $app->id }}')">
                                            <i class="fas fa-file-alt"></i>
                                        </button>
                                        @if($app->status_permohonan == 'SELESAI')
                                        <button type="button"
                                                class="btn btn-sm btn-success"
                                                data-toggle="tooltip" title="Cetak SKPT"
                                                onclick="printSkpt('{{ $app->id }}')">
                                            <i class="fas fa-print"></i>
                                        </button>
                                        @endif
                                    </div>
                                </td>
                            </tr>
                            @empty
                            <tr>
                                <td colspan="10" 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 SKPT 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 -->
<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 bg-primary text-white">
                <h5 class="modal-title">Detail Permohonan SKPT</h5>
                <button type="button" class="close text-white" data-dismiss="modal">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" id="detailContent">
                <!-- Content will be loaded dynamically -->
            </div>
        </div>
    </div>
</div>

<!-- Preview Modal -->
<div class="modal fade" id="previewModal" tabindex="-1" role="dialog" aria-labelledby="previewModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
            <!-- Modal Header with Orange Background -->
            <div class="modal-header text-white" style="background: linear-gradient(135deg, #ff8a00, #e67700);">
                <div class="d-flex justify-content-between align-items-center w-100">
                    <div>
                        <h5 class="modal-title font-weight-bold mb-0" id="previewModalLabel">Dokumen SKPT</h5>
                        <small id="previewSubtitle">Pemohon: - • No. SKPT: -</small>
                    </div>
                    <div class="d-flex align-items-center">
                        <span class="badge badge-light text-dark px-3 py-2 mr-3" id="previewStatus">
                            <i class="fas fa-check-circle text-success mr-1"></i>
                            <span id="statusText">SELESAI</span>
                        </span>
                        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                </div>
            </div>

            <!-- Modal Body -->
            <div class="modal-body p-0">
                <!-- Document Preview Section -->
                <div class="border-bottom">
                    <div class="p-4">
                        <div class="d-flex align-items-center justify-content-between bg-light rounded p-3">
                            <div class="d-flex align-items-center">
                                <div class="preview-icon mr-3">
                                    <i class="fas fa-file-pdf fa-2x text-danger"></i>
                                </div>
                                <div>
                                    <h6 class="mb-1 font-weight-bold">Surat SKPT</h6>
                                    <small class="text-muted">Dokumen PDF tersedia</small>
                                </div>
                            </div>
                            <div class="preview-actions">
                                <button type="button" class="btn btn-outline-primary btn-sm mr-2" onclick="viewPreview()">
                                    <i class="fas fa-eye mr-1"></i> View
                                </button>
                                <button type="button" class="btn btn-success btn-sm mr-1" onclick="verifyDocument('approved')" id="btnBenar">
                                    <i class="fas fa-check mr-1"></i> Benar
                                </button>
                                <button type="button" class="btn btn-danger btn-sm" onclick="verifyDocument('needs_revision')" id="btnBelumSesuai">
                                    <i class="fas fa-times mr-1"></i> Belum Sesuai
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Preview Frame -->
                <div id="previewFrame" style="height: 500px; display: none;">
                    <iframe id="documentFrame" src="" width="100%" height="100%" frameborder="0"></iframe>
                </div>
            </div>

            <!-- Modal Footer -->
            <div class="modal-footer bg-white">
                <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">
                    <i class="fas fa-times mr-1"></i> Tutup
                </button>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
// Global variables
let currentAppId = null;

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

function showDetail(id) {
    $.ajax({
        url: '{{ route("penerbitan-skpt.show", ":id") }}'.replace(':id', id),
        method: 'GET',
        success: function(response) {
            $('#detailContent').html(response);
            $('#detailModal').modal('show');
        },
        error: function(xhr) {
            Swal.fire({
                icon: 'error',
                title: 'Error!',
                text: 'Gagal memuat detail data.',
                confirmButtonColor: '#e74a3b',
            });
        }
    });
}

function showPreviewModal(id) {
    currentAppId = id;

    // Load application data first
    $.ajax({
        url: '{{ route("penerbitan-skpt.show", ":id") }}'.replace(':id', id),
        method: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json'
        },
        success: function(data) {
            // Update modal content
            $('#previewSubtitle').text(`Pemohon: ${data.nama_pemohon} • No. SKPT: ${data.no_registrasi}`);

            // Update status
            if (data.status_permohonan === 'SELESAI') {
                $('#statusText').text('SELESAI');
                $('#previewStatus').removeClass('badge-warning').addClass('badge-light');
                $('#previewStatus i').removeClass('text-warning').addClass('text-success');
            } else {
                $('#statusText').text('BELUM SELESAI');
                $('#previewStatus').removeClass('badge-light').addClass('badge-warning');
                $('#previewStatus i').removeClass('text-success').addClass('text-warning');
            }

            // Reset modal state
            $('#previewFrame').hide();
            $('#btnBenar').removeClass('btn-secondary').addClass('btn-success').prop('disabled', false);
            $('#btnBelumSesuai').removeClass('btn-secondary').addClass('btn-danger').prop('disabled', false);

            // Show modal
            $('#previewModal').modal('show');
        },
        error: function(xhr) {
            Swal.fire({
                icon: 'error',
                title: 'Error!',
                text: 'Gagal memuat data aplikasi.',
                confirmButtonColor: '#e74a3b',
            });
        }
    });
}

function viewPreview() {
    if (!currentAppId) return;

    // Show loading
    $('#previewFrame').show();
    $('#documentFrame').attr('src', 'about:blank');

    // Show loading animation in iframe
    setTimeout(() => {
        const loadingHtml = `
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <style>
                    body {
                        margin: 0;
                        padding: 20px;
                        font-family: Arial, sans-serif;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        min-height: 100vh;
                        background-color: #f8f9fa;
                    }
                    .loading-container {
                        text-align: center;
                        color: #6c757d;
                    }
                    .spinner {
                        border: 4px solid #f3f3f3;
                        border-top: 4px solid #ff8a00;
                        border-radius: 50%;
                        width: 40px;
                        height: 40px;
                        animation: spin 1s linear infinite;
                        margin: 0 auto 20px;
                    }
                    @keyframes spin {
                        0% { transform: rotate(0deg); }
                        100% { transform: rotate(360deg); }
                    }
                </style>
            </head>
            <body>
                <div class="loading-container">
                    <div class="spinner"></div>
                    <p>Memuat preview dokumen...</p>
                </div>
            </body>
            </html>
        `;

        $('#documentFrame')[0].src = 'data:text/html;charset=utf-8,' + encodeURIComponent(loadingHtml);
    }, 100);

    // Load the actual preview after a short delay
    setTimeout(() => {
        const previewUrl = '{{ route("penerbitan-skpt.preview", ":id") }}'.replace(':id', currentAppId);
        $('#documentFrame').attr('src', previewUrl);
    }, 800);
}

function verifyDocument(status) {
    if (!currentAppId) {
        Swal.fire('Error!', 'ID aplikasi tidak ditemukan.', 'error');
        return;
    }

    const statusText = status === 'approved' ? 'BENAR' : 'BELUM SESUAI';
    const confirmText = status === 'approved' ? 'Ya, Dokumen Benar!' : 'Ya, Belum Sesuai!';
    const confirmColor = status === 'approved' ? '#28a745' : '#dc3545';

    Swal.fire({
        title: `Verifikasi Dokumen - ${statusText}`,
        text: `Apakah Anda yakin dokumen ini ${statusText.toLowerCase()}?`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: confirmColor,
        cancelButtonColor: '#6c757d',
        confirmButtonText: confirmText,
        cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.isConfirmed) {
            // Show loading
            Swal.fire({
                title: 'Menyimpan Verifikasi...',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });

            // Send verification data to server
            $.ajax({
                url: '{{ route("penerbitan-skpt.verify", ":id") }}'.replace(':id', currentAppId),
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                data: JSON.stringify({
                    verification_status: status,
                    verification_notes: `Dokumen telah diverifikasi sebagai ${statusText}`,
                    verification_date: '{{ date('Y-m-d') }}'
                }),
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Berhasil!',
                            text: response.message,
                            confirmButtonColor: '#28a745',
                        }).then(() => {
                            // Update button states
                            if (status === 'approved') {
                                $('#btnBenar').removeClass('btn-success').addClass('btn-secondary').prop('disabled', true);
                                $('#btnBenar').html('<i class="fas fa-check-circle mr-1"></i> Sudah Diverifikasi');
                                $('#btnBelumSesuai').prop('disabled', true);
                            } else {
                                $('#btnBelumSesuai').removeClass('btn-danger').addClass('btn-secondary').prop('disabled', true);
                                $('#btnBelumSesuai').html('<i class="fas fa-times-circle mr-1"></i> Perlu Revisi');
                                $('#btnBenar').prop('disabled', true);
                            }
                            location.reload();
                        });
                    } else {
                        Swal.fire('Error!', response.message, 'error');
                    }
                },
                error: function(xhr) {
                    let errorMessage = 'Gagal menyimpan verifikasi.';

                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMessage = xhr.responseJSON.message;
                    } else if (xhr.responseJSON && xhr.responseJSON.errors) {
                        const errors = Object.values(xhr.responseJSON.errors).flat();
                        errorMessage = errors.join('\n');
                    }

                    Swal.fire('Error!', errorMessage, 'error');
                }
            });
        }
    });
}

function printSkpt(id) {
    Swal.fire({
        title: 'Cetak SKPT',
        text: 'Apakah Anda yakin ingin mencetak SKPT ini?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#28a745',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Ya, Cetak!',
        cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.isConfirmed) {
            // Open print page in new tab
            window.open('{{ route("penerbitan-skpt.print", ":id") }}'.replace(':id', id), '_blank');
        }
    });
}

// Event handlers for modal
$('#previewModal').on('hidden.bs.modal', function () {
    // Reset modal state when closed
    currentAppId = null;
    $('#previewFrame').hide();
    $('#documentFrame').attr('src', 'about:blank');
});

// Success/Error Messages
@if(session('success'))
    $(document).ready(function() {
        Swal.fire({
            icon: 'success',
            title: 'Sukses!',
            text: '{{ session('success') }}',
            confirmButtonText: 'OK',
            confirmButtonColor: '#28a745',
        });
    });
@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;
    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
}

.table th {
    font-size: 12px;
    font-weight: 600;
    text-transform: uppercase;
    padding: 12px 8px;
    border: none;
}

.table td {
    font-size: 13px;
    padding: 10px 8px;
    border: none;
    vertical-align: middle;
}

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

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

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

.form-label {
    color: #495057;
    margin-bottom: 4px;
}

.btn-sm {
    padding: 0.25rem 0.5rem;
    font-size: 0.75rem;
}

/* Custom orange theme colors */
.btn-primary {
    background-color: #ff8a00;
    border-color: #ff8a00;
}

.btn-primary:hover {
    background-color: #e67700;
    border-color: #e67700;
}

.text-primary {
    color: #ff8a00 !important;
}

.bg-primary {
    background-color: #ff8a00 !important;
}

/* Table striping with subtle colors */
.bg-light {
    background-color: #f8f9fa !important;
}

/* Preview Modal Styles */
.preview-icon {
    opacity: 0.8;
}

.preview-actions .btn {
    min-width: 80px;
}

#previewFrame {
    border-top: 1px solid #dee2e6;
}

.modal-xl {
    max-width: 90%;
}

.alert {
    border-radius: 0.5rem;
}

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

    .table th, .table td {
        padding: 8px 4px;
        font-size: 11px;
    }

    .btn-sm {
        padding: 0.2rem 0.4rem;
    }

    .modal-xl {
        max-width: 95%;
    }

    .preview-actions {
        flex-direction: column;
    }

    .preview-actions .btn {
        margin-bottom: 0.5rem;
        width: 100%;
    }
}
</style>
@endpush
