@extends('layouts.master')
@section('css')
    {{-- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/magnific-popup.min.css"> --}}
@endsection

@section('title')
    Dashboard
@endsection

@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">{!! $title !!}</li>
                </ol>
            </div>
            <div class="col-md-4">
                <div class="text-end d-flex justify-content-end">
                    <a href="{{ URL::to('mahasiswa/proposal/create') }}" type="button" class="btn btn-primary waves-effect waves-light"> <i class="fas fa-plus-circle"></i> Tambah Data</a>
                </div>
            </div>
        </div>
    </div>
    <!-- end page title -->

    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    <form action="{{ route('mahasiswa.proposal.index') }}">
                        <div class="row">
                            <div class="col-md-8"></div>
                            <div class="col-md-4 text-right">
                                <div class="row">
                                    <label class="col-sm-3 col-form-label"></label>
                                    <label class="col-sm-3 col-form-label">Tahun : </label>
                                    <div class="col-sm-6">
                                        <select class="form-select" name="year" onchange="this.form.submit()">
                                        @foreach($periode as $per)
                                            <option value="{{ $per->nama }}" {{ $year == $per->nama ? 'selected' : '' }}>{{ $per->nama }}</option>
                                        @endforeach
                                    </select>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                    <br>
                    <div class="table-responsive">
                        <table id="datatable" class="table table-bordered dt-responsive nowrap" style="border-collapse: collapse; border-spacing: 0; width: 100%;">
                            <thead style="text-align: center; vertical-align: middle;">
                                <tr>
                                    <th>No</th>
                                    <th width="5%">Kode Kelompok</th>
                                    <th>Identitas Ketua</th>
                                    <th>Identitas Dosen Pembimbing</th>
                                    <th>Kategori PMW</th>
                                    <th>Judul Proposal</th>
                                    <th>Usulan Anggaran</th>
                                    <th>Status</th>
                                    <th>Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach ($proposal as $item)
                                @php $token = Str::random(30); @endphp
                                <tr id="row-{{ $token }}">
                                    <td style="text-align: center;">{{ $loop->iteration }}.</td>
                                    <td style="text-align: center;">{{ $item->rKelompok->kode }}</td>
                                    <td>{{ $item->rKelompok->rBiodata->name }} <br> {{ $item->rKelompok->rBiodata->noidentitas }} <br> {{ $item->rKelompok->rBiodata->fakultas }} <br> {{ $item->rKelompok->rBiodata->prodi }}</td>
                                    <td style="text-align: center;">{{ $item->rKelompok->nama_dosen }} <br> {{ $item->rKelompok->nidn_dosen }}</td>
                                    <td style="text-align: center;">{{ $item->rJenis->nama }}</td>
                                    <td style="text-align: center;">{{ $item->judul }}</td>
                                    <td style="text-align: center;">
                                        @if(substr(number_format($item->usulan_dana, 2, ',', '.'), -3) === ',00')
                                            Rp{{ substr(number_format($item->usulan_dana, 2, ',', '.'), 0, -3) }},-
                                        @else
                                            Rp{{ number_format($item->usulan_dana, 2, ',', '.') }}
                                        @endif
                                    </td>
                                    <td>
                                        @if(is_null($item->upload_dokumen))
                                            <span class="badge bg-danger">Belum Upload Proposal</span><br>
                                            <strong> Keterangan : </strong><br>
                                            Upload proposal pada : -<br>
                                            Disetujui proposal pada : -<br>
                                        @else
                                            @if($item->status == '0')
                                                <span class="badge bg-warning">Menunggu Persetujuan Dosen</span><br>
                                                <strong> Keterangan : </strong><br>
                                                Upload proposal pada : <h6 class="text-primary"> {{ $item->date_upload }} </h6>
                                                Disetujui proposal pada : <h6 class="text-primary"> {{ $item->date_approval }} </h6>
                                            @elseif($item->status == '2')
                                                <span class="badge bg-danger">Ditolak Dosen</span><br>
                                                <strong> Keterangan : </strong><br>
                                                Upload proposal pada : <h6 class="text-primary"> {{ $item->date_upload }} </h6>
                                                Komentar : <h6 class="text-primary"> {{ $item->alasan_revisi }} </h6>
                                            @else
                                                <span class="badge bg-success">Sudah Disetujui Dosen</span><br>
                                                {{-- <span class="badge bg-warning">Menunggu Persetujuan Dosen</span> <br> --}}
                                                <strong> Keterangan : </strong><br>
                                                Upload proposal pada : <h6 class="text-primary"> {{ $item->date_upload }} </h6>
                                                Disetujui proposal pada : <h6 class="text-primary"> {{ $item->date_approval }} </h6>
                                            @endif
                                        @endif
                                    </td>
                                    <td style="text-align: center;">
                                        <button data-bs-toggle="modal" data-bs-target="{{ '#lihat'.$item->proposal_id }}" href="{{ URL::to('mahasiswa/kelompok-new', encrypt($item->proposal_id)) }}" class="btn btn-info btn-sm"><i class="far fa-eye"></i> Lihat</button>

                                        @if(is_null($item->status) || $item->status == '2')
                                        <a href="{{ URL::to('mahasiswa/proposal/'.encrypt($item->proposal_id).'/edit') }}" class="btn btn-warning btn-sm">Revisi</a>
                                            <a onclick="hapus('{{ encrypt($item->proposal_id) }}', 'row-{{ $token }}')" class="btn btn-danger btn-sm">Hapus</a>
                                        @endif

                                        <div id="{{ 'lihat'.$item->proposal_id }}" class="modal fade" tabindex="-1" role="dialog"
                                            aria-labelledby="lihatLabel" aria-hidden="true">
                                            <div class="modal-dialog modal-lg modal-dialog-centered">
                                                <div class="modal-content">
                                                    <div class="modal-header">
                                                        <h5 class="modal-title" id="lihatLabel">Detail Proposal </h5>
                                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                    </div>
                                                    <div class="modal-body">
                                                        <p>
                                                            <div class="table-responsive">
                                                                <table class="table mb-0">
                                                                    <tr>
                                                                        <th>Judul Proposal</th>
                                                                        <td>{{ $item->judul }}</td>
                                                                    </tr>
                                                                    <tr>
                                                                        <th>Kategori PMW</th>
                                                                        <td>{{ $item->rJenis->nama }}</td>
                                                                    </tr>
                                                                    <tr>
                                                                        <th>Status</th>
                                                                        <td>
                                                                            @if(is_null($item->status) OR $item->status == '0')
                                                                            <span class="badge bg-danger">Menunggu Persetujuan Dosen</span>
                                                                            @else
                                                                                <span class="badge bg-success">Sudah Disetujui Dosen</span>
                                                                            @endif
                                                                        </td>
                                                                    </tr>
                                                                    <tr>
                                                                        <th>Proposal</th>
                                                                        <td>
                                                                            @if($item->upload_dokumen)
                                                                                <a href="https://statik.unesa.ac.id/simpmw/proposal/{{ $item->rPeriode->nama }}/{{ $item->upload_dokumen }}"  target="_blank" class="btn btn-success btn-sm"> <i class="far fa-eye"></i> Lihat Proposal</a>
                                                                                {{-- <iframe id="view-pdf" width="100%" height="400px" src="https://statik.unesa.ac.id/simpmw/proposal/{{ $item->rPeriode->nama }}/{{ $item->upload_dokumen }}" frameborder="0"></iframe> --}}
                                                                            @else
                                                                                <div class="alert alert-danger alert-dismissible fade show mb-0" role="alert">
                                                                                    <strong>Informasi!</strong> File tidak ditemukan.
                                                                                </div>
                                                                            @endif
                                                                        </td>
                                                                    </tr>
                                                                    <tr>
                                                                        <th>Video Produk</th>
                                                                        <td>
                                                                            @if($item->upload_dokumen)
                                                                            {{-- @php
                                                                                @dd($item->rProposalUrl->url);
                                                                            @endphp --}}
                                                                                <button id="preview-video" class="btn btn-success btn-sm" data-video="{{ $item->rProposalUrl->url }}">
                                                                                {{-- <button id="preview-video" class="btn btn-success btn-sm" data-video="https://youtu.be/9CHu8iOsxDE?feature=shared"> --}}
                                                                                    <i class="far fa-eye"></i> Lihat Video
                                                                                </button>
                                                                            @else
                                                                                <div class="alert alert-danger alert-dismissible fade show mb-0" role="alert">
                                                                                    <strong>Informasi!</strong> File tidak ditemukan.
                                                                                </div>
                                                                            @endif
                                                                        </td>
                                                                    </tr>
                                                                </table>
                                                            </div>
                                                        </p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div> <!-- end col -->
    </div> <!-- end row -->
@endsection

@section('js')
<script>
    function hapus(id, rowId){
        Swal.fire({
            title: 'Apakah anda yakin untuk menghapus usulan ini?',
            text: "file yang sudah terupload juga terhapus",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'OK',
        }).then((result) => {
            if (result.isConfirmed) {
                var token = '{{ csrf_token() }}';
                var request = $.ajax({
                    url: '{{ route('mahasiswa.proposal.hapus') }}',
                    type: 'POST',
                    dataType: 'html',
                    data: {id:id, _token:token},
                    success: function(data){
                        Swal.fire({
                            title: 'Data Berhasil Di Hapus',
                            icon: 'success',
                            showConfirmButton: false,
                            timer: 1500
                        });

                        $('#'+rowId).remove();
                    },
                    error: function(xhr, status, error){
                        Swal.fire({
                            position: 'top-end',
                            icon: 'error',
                            title: xhr.responseText,
                            showConfirmButton: false,
                            timer: 3500
                        });
                    }
                });
            }
        })
    }
</script>

<!-- Kode JavaScript untuk Magnific Popup -->
@if (count($proposal) > 0)
    <script>
    $(document).ready(function() {
    // Event handler untuk tombol "Lihat Video" dengan ID preview-video
    $('#preview-video').on('click', function() {
        var videoUrl = $(this).attr('data-video');
        // console.log(videoUrl);

        if (videoUrl) {
            // Buka video dalam Magnific Popup
            if (videoUrl.includes('youtu.be')) {
                // Konversi ke format youtube.com/watch?v=xxxxx
                videoUrl = videoUrl.replace('youtu.be/', 'youtube.com/watch?v=');
            }

            // Menghapus parameter query dari URL
            if (videoUrl.includes('youtu.be')) {
                videoUrl = videoUrl.split('?')[0];
            } else if (videoUrl.includes('youtube.com/watch?v=')) {
                videoUrl = videoUrl.split('&')[0];
            }

            // Buka video dalam Magnific Popup jika valid, buka di tab baru jika tidak
            if (isValidYouTubeUrl(videoUrl)) {
                $.magnificPopup.open({
                    items: {
                        src: videoUrl
                    },
                    type: 'iframe',
                    iframe: {
                        markup: '<div class="mfp-iframe-scaler">'+
                                    '<div class="mfp-close"></div>'+
                                    '<iframe class="mfp-iframe" frameborder="0" allowfullscreen allow="autoplay"></iframe>'+
                                '</div>'
                    },
                    callbacks: {
                        open: function() {
                            // Sembunyikan modal lama saat Magnific Popup dibuka
                            $('#{{ 'lihat'.$item->proposal_id }}').modal('hide');

                            // Mulai autoplay video setelah Magnific Popup dibuka
                            var iframe = this.content.find('iframe');
                            if (iframe.length > 0) {
                                var videoSrc = iframe.attr('src');
                                iframe.attr('src', videoSrc + '&autoplay=1'); // Tambahkan autoplay=1 ke URL video
                            }
                        },
                        close: function() {
                            // Tampilkan kembali modal lama setelah Magnific Popup ditutup
                            $('#{{ 'lihat'.$item->proposal_id }}').modal('show');

                            // Hentikan autoplay video saat Magnific Popup ditutup
                            var iframe = this.content.find('iframe');
                            if (iframe.length > 0) {
                                var videoSrc = iframe.attr('src');
                                iframe.attr('src', videoSrc.replace('&autoplay=1', '')); // Hapus autoplay=1 dari URL video
                            }
                        }
                    }
                });
            } else {
                // Buka video di tab baru jika tidak valid
                window.open(videoUrl, '_blank');
            }
        } else {
            console.error('URL video tidak valid:', videoUrl);
            }
        });

        function isValidYouTubeUrl(url) {
            // Lakukan validasi sederhana menggunakan ekspresi reguler
            return /^(http(s)?:\/\/)?((w){3}\.)?youtu(be|\.be)?(\.com)?\/.+/gm.test(url);
        }
    });

</script>
@endif

{{-- <script>
    document.addEventListener("DOMContentLoaded", function() {
        var openModalBtn = document.getElementById("openModalBtn");
        var closeModalBtn = document.getElementById("closeModalBtn");
        var modal = document.getElementById("myModal");

        openModalBtn.addEventListener("click", function() {
            modal.style.display = "block";

            // Mengambil URL dari objek $item
            var proposalUrl = "{{ $item->rProposalUrl->url }}";

            // Load konten eksternal ke dalam div modalContent
            var xhr = new XMLHttpRequest();
            xhr.open("GET", proposalUrl, true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    document.getElementById("externalContent").innerHTML = xhr.responseText;
                }
            };
            xhr.send();
        });

        closeModalBtn.addEventListener("click", function() {
            modal.style.display = "none";
        });

        window.addEventListener("click", function(event) {
            if (event.target == modal) {
                modal.style.display = "none";
            }
        });
    });
</script>     --}}
@endsection
