@extends('layouts.master')

@section('title', 'Dashboard')

@section('header')
<div class="page-title">
    <h3>Dashboard</h3>
</div>
@endsection

@section('contents')
<!-- start page title -->
<div class="page-title-box">
    <div class="row align-items-center">
        <div class="col-md-8">
            <h6 class="page-title">{!! $title !!}</h6>
            <ol class="breadcrumb m-0">
                <li class="breadcrumb-item">Mahasiswa</li>
                <li class="breadcrumb-item"><a href="{{ url()->previous() }}">Monev Internal I</a></li>
                <li class="breadcrumb-item">{!! $title !!}</li>
            </ol>
        </div>
        <div class="col-md-4">
            <div class="float-end d-none d-md-block">
                <button type="button" class="btn btn-primary waves-effect waves-light" data-bs-toggle="modal" data-bs-target="#tmbhKel"><i class="fas fa-plus-circle me-2"></i> Tambah Data</button>
            </div>
        </div>
    </div>
</div>
<!-- end page title -->

<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table id="datatable" class="table table-bordered dt-responsive nowrap" style="border-collapse: collapse; border-spacing: 0; width: 100%;">
                        <thead>
                            <tr align="center" valign="middle">
                                <th>No</th>
                                <th>Jenis</th>
                                <th>Judul</th>
                                <th>Keterangan</th>
                                <th>File</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            {{-- @if ($proposal->rLuaran->count()) --}}
                            @foreach ($proposal->rLuaran as $item)
                            @php $token = Str::random(30); @endphp
                            <tr id="row-{{ $token }}" align="center" valign="middle">
                                <td>{{ $loop->iteration }}</td>
                                <td>{{ $item->jenis_luaran }}</td>
                                <td>{{ $item->judul }}</td>
                                <td>{{ $item->keterangan_luaran }}</td>
                                <td><a href="https://statik.unesa.ac.id/simpmw/luaran/{{ $item->jenis_luaran }}/{{ $item->file_luaran }}" target="_blank" title="Logbook" class="btn btn-info btn-sm waves-effect waves-light"> <i class="fas fa-search"></i> Lihat</a></td>
                                <td>
                                    <a class="btn btn-warning btn-sm fas fa-pencil-alt"> Edit</a>
                                    <a onclick="hapus('{{ encrypt($item->id) }}', 'row-{{ $token }}')" class="btn btn-danger btn-sm fas fa-trash-alt"> Hapus</a>
                                </td>
                            </tr>
                            @endforeach
                            {{-- @else
                            <tr>
                                <td colspan="6" style="text-align: center; font-style: italic;">Tidak ada data yang dapat diambil.</td>
                            </tr>
                            @endif --}}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div> <!-- end col -->
</div> <!-- end row -->

<div id="tmbhKel" class="modal fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="{{ route('mahasiswa.luaran.store') }}" method="POST" enctype="multipart/form-data">
                @csrf
                <div class="modal-header">
                    <h5 class="modal-title" id="myModalLabel">Tambah Laporan Magang / Luaran</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input class="form-control" type="hidden" name="proposal_id" id="proposal_id" value="{{ $proposal->proposal_id }}">
                    <div class="col-12">
                        <h5 class="font-size-16">Jenis Laporan/Luaran : </h5>
                        <p><select class="form-select" aria-label="Default select example" name="jenis_luaran" id="jenis_luaran_select" required>
                                <option value="">--Pilih--</option>
                                <option value="Laporan Magang">Laporan Magang</option>
                                <option value="Buku">Buku</option>
                                <option value="Jurnal">Jurnal</option>
                                <option value="Video">Video</option>
                                <option value="Produk">Produk</option>
                                <option value="Media">Publikasi Media</option>
                                <option value="Lainnya">Lainnya</option>
                            </select></p>
                    </div>
                    <div class="col-12" id="lainnya_form" style="display: none;">
                        <h5 class="font-size-16">Jenis Laporan/Luaran Lainnya : </h5>
                        <p>
                            <input class="form-control" type="text" name="jenis_luaran_lainnya" id="jenis_luaran_lainnya" value="{{ old('jenis_luaran_lainnya') }}">
                        </p>
                    </div>
                    <div class="col-12">
                        <h5 class="font-size-16">Judul : </h5>
                        <p>
                            <input class="form-control" type="text" name="judul" id="judul" value="{{ old('judul') }}" required>
                        </p>
                    </div>
                    <div class="col-12">
                        <h5 class="font-size-16">Upload File : </h5>
                        <div class="row">
                            <div class="col-8">
                                <p>
                                    <input type="file" name="file" class="form-control" id="input-file">
                                    @if ($errors->has('file')) <span class="text-danger">{{ $errors->first('file') }}</span> @endif
                                </p>
                            </div>
                            <div class="col-4">
                                <button type="button" class="btn btn-warning form-control" id="btnPreview">Preview</button>
                            </div>
                        </div>
                    </div>
                    <div class="col-12">
                        <h5 class="font-size-16">Keterangan : </h5>
                        <p>
                            <textarea id="textarea" class="form-control" maxlength="225" rows="3" name="keterangan_luaran" required></textarea>
                        </p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary waves-effect" data-bs-dismiss="modal">Tutup</button>
                    <button type="submit" class="btn btn-primary waves-effect waves-light">Simpan</button>
                </div>
            </form>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>

<!-- Modal Preview -->
<div class="modal fade" id="pdfModal" tabindex="-1" role="dialog" aria-labelledby="pdfModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
        <div class="modal-content" style="height: 80vh;">
            <div class="modal-header">
                <h5 class="modal-title" id="pdfModalLabel">Preview PDF</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">{{-- <span aria-hidden="true">&times;</span> --}}</button>
            </div>
            <div class="modal-body">
                {{-- <iframe id="pdfViewer" width="100%" height="100%" frameborder="0"></iframe> --}}
                {{-- <iframe id="view-pdf" width="100%" height="450" frameborder="0" src="{{ $proposal ? 'https://statik.unesa.ac.id/simpkm/proposal/'.$proposal->rPeriode->nama.'/'.$proposal->upload_dokumen : '' }} "></iframe> --}}
                <iframe id="view-pdf" width="100%" height="100%"></iframe>
            </div>
        </div>
    </div>
</div>

@endsection

@section('js')
{{-- <script src="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/jquery.magnific-popup.min.js"></script> --}}
<script>
    $(document).ready(function () {
        $('#input-file').on('change', function (e) {
            var fileInput = e.target.files[0];

            // Periksa apakah ada file yang dipilih
            if (!fileInput) {
                alert('Silakan pilih file PDF terlebih dahulu.');
                return;
            }

            // Periksa tipe file (harus PDF)
            if (fileInput.type !== 'application/pdf') {
                alert('File harus berupa PDF.');
                // Reset input file
                $('#input-file').val('');
                return;
            }

            // Periksa ukuran file (maksimal 5MB)
            if (fileInput.size > 5 * 1024 * 1024) {
                alert('Ukuran file maksimal adalah 5MB.');
                // Reset input file
                $('#input-file').val('');
                return;
            }
        });

        // Fungsi untuk tombol "Preview"
        $('#btnPreview').click(function() {
            var fileInput = $('#input-file')[0].files[0];

            // Periksa apakah ada file yang dipilih
            if (!fileInput) {
                alert('Silakan pilih file PDF terlebih dahulu.');
                return;
            }

            // Sembunyikan modal "Tambah Luaran"
            $('#tmbhKel').modal('hide');

            // Tampilkan pratinjau PDF di dalam modal jika file memenuhi syarat
            var url = URL.createObjectURL(fileInput);
            $('#view-pdf').attr('src', url);
            $('#pdfModal').modal('show');
        });

        // Event saat modal preview ditutup
        $('#pdfModal').on('hidden.bs.modal', function (e) {
            // Tampilkan kembali modal "Tambah Luaran"
            $('#tmbhKel').modal('show');

            // Reset iframe saat modal ditutup
            $('#view-pdf').attr('src', '');
        });
    });
</script>
<script>
    function hapus(id, rowId) {
    Swal.fire({
        title: 'Apakah Anda yakin untuk menghapus usulan ini?',
        text: "File yang sudah terupload juga akan terhapus",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'OK',
    }).then((result) => {
        if (result.isConfirmed) {
            var token = '{{ csrf_token() }}';
            $.ajax({
                url: '{{ route('mahasiswa.luaran.hapus') }}',
                type: 'POST',
                dataType: 'json',
                data: {
                    id: id,
                    _token: token
                },
                success: function(response) {
                    if (response.status === 'success') {
                        Swal.fire({
                            title: 'Data Berhasil Dihapus',
                            icon: 'success',
                            showConfirmButton: false,
                            timer: 1500
                        }).then(() => {
                            location.reload(); // Refresh halaman setelah pesan sukses ditampilkan
                        });
                    } else {
                        Swal.fire({
                            title: 'Gagal',
                            text: response.message,
                            icon: 'error',
                            showConfirmButton: false,
                            timer: 3500
                        });
                    }
                },
                error: function(xhr, status, error) {
                    Swal.fire({
                        position: 'top-center',
                        icon: 'error',
                        title: 'Terjadi Kesalahan',
                        text: xhr.responseText,
                        showConfirmButton: false,
                        timer: 3500
                    });
                }
            });
        }
    })
}

    document.getElementById('jenis_luaran_select').addEventListener('change', function() {
        var select = this;
        var lainnyaForm = document.getElementById('lainnya_form');
        var lainnyaInput = document.getElementById('jenis_luaran_lainnya');

        if (select.value === 'Lainnya') {
            lainnyaForm.style.display = 'block';
            lainnyaInput.setAttribute('required', 'required');
        } else {
            lainnyaForm.style.display = 'none';
            lainnyaInput.removeAttribute('required');
        }
    });

    document.getElementById('jenis_luaran_select').addEventListener('focus', function() {
        var select = this;
        if (select.options[0].value === '') {
            select.removeChild(select.options[0]);
        }
    });

    document.addEventListener('DOMContentLoaded', function() {
    var table = document.getElementById('datatable');
    var thead = table.querySelector('thead');
    var tbody = table.querySelector('tbody');
    
    // Menghitung jumlah elemen <th> dalam <thead>
    var thCount = thead.querySelectorAll('th').length;

    // Periksa apakah tbody kosong
    if (!tbody.querySelector('tr')) {
        var tr = document.createElement('tr');
        var td = document.createElement('td');
        
        // Set colspan sesuai dengan jumlah <th>
        td.setAttribute('colspan', thCount);
        td.style.textAlign = 'center';
        td.style.fontStyle = 'italic';
        td.textContent = 'Tidak ada data yang dapat diambil.';
        
        tr.appendChild(td);
        tbody.appendChild(tr);
    }
});

</script>
@endsection
