@extends('layouts.master')

@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="float-end d-none d-md-block">
                </div>
            </div>
        </div>
    </div>
    <!-- end page title -->

    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    <form action="{{ route('dosen.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" style="border-collapse: collapse; border-spacing: 0; width: 100%;">
                            <thead style="text-align: center; vertical-align: middle;">
                            <tr>
                                <th>No</th>
                                <th>Kode Kelompok</th>
                                <th>Identitas Ketua</th>
                                {{-- <th>Identitas Dosen Pembimbing</th> --}}
                                <th>Kategori PMW</th>
                                <th>Judul Proposal</th>
                                <th>Usulan Dana</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>{{ $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 == '1')
                                                <span class="badge bg-success">Sudah Disetujui 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-warning">Menunggu Persetujuan Dosen</span> <br>
                                                <strong> Keterangan : </strong>  <br>
                                                Upload proposal pada : <h6 class="text-primary"> {{ $item->date_upload }} </h6>
                                                Disetujui proposal pada :
                                            @endif
                                        @endif
                                    </td>
                                    <td>
                                        <a data-toggle="tooltip"  data-id="{{ $item->proposal_id }}" data-original-title="Lihat" class="btn btn-info btn-sm form-control mb-2 lihatDet"><i class="far fa-eye"></i> Lihat</a>
                                        @if($item->status == '0')
                                            <a onclick="setuju('{{ encrypt($item->proposal_id) }}', 'row-{{ $token }}')" class="btn btn-success btn-sm form-control mb-2"><i class="fas fa-check"></i> Setuju</a>
                                            <a href="" id="revPro" data-toggle="modal" data-target='#practice_modal' data-id="{{ encrypt($item->proposal_id) }}" class="btn btn-danger btn-sm form-control"><i class="fas fa-times"></i> Tolak</a>
                                        @endif
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div> <!-- end col -->
    </div> <!-- end row -->

    <div id="lihatDetail" class="modal fade">
        <div class="modal-dialog modal-xl 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" id="tableDetail">
                                <tbody>

                                </tbody>
                            </table>
                        </div>
                    </p>
                </div>
            </div>
        </div>
    </div>

    <div id="tolakPro" class="modal fade">
        <div class="modal-dialog modal-xl">
            <form id="companydata" action="{{ route('dosen.proposal.tolak') }}" method="POST">
                @csrf
                <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>
                            <input type="hidden" id="proposal_id" name="proposal_id" value="">
                            <label for="kode" class="col-sm-8 col-form-label">Apakah yakin akan menolak proposal ?</label>
                            <div class="row mb-3">
                                <input class="form-control" type="text" id="judul" name="judul" disabled>
                            </div>
                            <div class="row mb-3">
                                <textarea id="textarea" name="alasan_revisi" class="form-control" maxlength="225" rows="3" placeholder="Alasan Revisi"></textarea>
                            </div>
                            <div class="col-sm-10">
                                <button type="submit" class="btn btn-danger waves-effect waves-light me-1"> Tolak </button>
                            </div>
                        </p>
                    </div>
                </div>
            </form>
        </div>
    </div>

@endsection

@section('js')

<script src="{{ asset('theme/js/pages/datatables.init.js') }}"></script>
<script>

function setuju(id, rowId){
        Swal.fire({
            title: 'Apakah anda yakin untuk menyetujui Kelompok ini?',
            text: "Kelompok yang di setujui akan di teruskan untuk upload proposal",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'OK',
        }).then((result) => {
            if (result.isConfirmed) {
                var token = '{{ csrf_token() }}';
                var request = $.ajax({
                    url: '{{ route('dosen.proposal.setuju') }}',
                    type: 'POST',
                    dataType: 'html',
                    data: {id:id, _token:token},
                    success: function(data){
                        Swal.fire({
                            position: 'top-center',
                            icon: 'success',
                            title: 'Kelompok berhasil di setujui',
                            showConfirmButton: false,
                            timer: 1500
                        });

                        location.reload();

                    },
                    error: function(xhr, status, error){
                        Swal.fire({
                            position: 'top-end',
                            icon: 'error',
                            title: xhr.responseText,
                            showConfirmButton: false,
                            timer: 3500
                        });
                    }
                });
            }
        })
    }

    $(document).ready(function() {
    $('#datatable').on('click','.lihatDet',function(){
        var proId = $(this).attr('data-id');

        if (proId != null || proId != '') {
            // Kosongkan data modal
            $('#tableDetail tbody').empty();

            $.ajax({
                url: "{{ route('dosen.proposal-lihat') }}",
                data: {
                    "proposal_id": proId,
                },
                dataType: 'json',
                success: function(response) {
                    // Tampilkan data di dalam modal
                    $('#tableDetail tbody').html(response.html);

                    // Tampilkan modal
                    $('#lihatDetail').modal('show');

                    // Inisialisasi Magnific Popup pada tombol "Lihat Video"
                    initMagnificPopup();
                }
            });
        }
    });

    // Fungsi untuk inisialisasi Magnific Popup pada tombol "Lihat Video"
    function initMagnificPopup() {
        $('#tableDetail').on('click', '#lihat', function() {
            var videoUrl = $(this).attr('data-video');
            // console.log(videoUrl);

            if (videoUrl) {
                // Cek jika URL video adalah format youtu.be
                if (videoUrl.includes('youtu.be')) {
                    // Konversi ke format youtube.com/watch?v=xxxxx
                    videoUrl = videoUrl.replace('youtu.be/', 'youtube.com/watch?v=');
                }

                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
                                $('#lihatDetail').modal('hide');

                                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 setelah Magnific Popup ditutup
                                $('#lihatDetail').modal('show');

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

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


    $('body').on('click', '#revPro', function (event) {

        event.preventDefault();
        var id = $(this).data('id');
        console.log(id)
        $.get('proposal-approv/' + id, function (data) {

            $('#userCrudModal').html("Edit category");
            $('#submit').val("Edit category");
            $('#tolakPro').modal('show');

            $('#proposal_id').val(data.data.proposal_id);
            $('#judul').val(data.data.judul);

        })
    });

</script>
@endsection
