@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>
    </div>
    <!-- end page title -->
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    @if ($proposal)
                    {!! Form::model($proposal, ['route' => ['mahasiswa.proposal.update', $proposal->proposal_id], 'method'=>'patch', 'files' => 'true', 'enctype'=>'multipart/form-data']) !!}
                    @else
                    {{ Form::open(['url' => route('mahasiswa.proposal.store'), 'method' => 'post', 'id' => 'proposal', 'files' => 'true', 'enctype'=>'multipart/form-data']) }}
                    @endif

                        @csrf
                    <h4 class="card-title">{!! $title !!}</h4>
                    <p class="card-title-desc"></p>
                    <div class="row mb-3">
                        <label for="kode" class="col-sm-2 col-form-label">Judul<span style="color: red;"> *</span></label>
                        <div class="col-sm-10">
                            <input class="form-control" type="text" id="judul" name="judul" value="{{ old('judul', $proposal ? $proposal->judul : '') }}" placeholder="Judul Produk" required>
                            <input class="form-control" type="hidden" id="kode_kelompok" name="kode_kelompok" value="{{ $proposal ? $proposal->kelompok_id : $kelompok->kelompok_id }}" >
                            <input class="form-control" type="hidden" id="periode_id" name="periode_id" value="{{ $proposal ? $proposal->periode_id : $periode->periode_id }}" >
                        </div>
                    </div>
                    <div class=" row mb-3">
                        <label class="col-sm-2 col-form-label">Kategori PMW<span style="color: red;"> *</span></label>
                        <div class="col-sm-10">
                            <select class="form-select select2" name="jenis">
                                <option selected>Pilih Jenis</option>
                                @foreach($jenis as $item => $pkm)
                                <option value="{{ $item }}" {{ $proposal ? $proposal->jenis_id == $item ? 'selected' : '' : '' }}>{{ $pkm }}</option>
                                @endforeach
                            </select>
                            @if ($errors->has('jenis')) <span class="text-danger"><i>{{ $errors->first('jenis') }}</i></span> @endif
                        </div>
                    </div>
                    <div class="row mb-3" class="dropzone">
                        <label for="kode" class="col-sm-2 col-form-label">Upload Proposal<span style="color: red;"> *</span></label>
                        <div class="col-sm-8 col-lg-8">
                            <input type="file" name="file" class="form-control" id="input-file" accept="application/pdf">
                            @if ($errors->has('file')) <span class="text-danger"><i>{{ $errors->first('file') }}</i></span> @endif
                            {{-- <iframe id="view-pdf" width="80%" height="80%" frameborder="0" src="{{ $proposal ? 'https://statik.unesa.ac.id/simpkm/proposal/'.$proposal->rPeriode->nama.'/'.$proposal->upload_dokumen : '' }} "></iframe> --}}
                        </div>
                        <div class="col-sm-2 col-lg-2">
                            <button type="button" class="form-control btn btn-warning" id="btnPreview">Preview</button>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <label for="kode" class="col-sm-2 col-form-label">URL Video Produk<span style="color: red;"> *</span></label>
                        <div class="col-sm-3 col-lg-3">
                            <input class="form-control" type="text" id="url_name" name="url_name" value="{{ old('url_name') }}" placeholder="Nama Video Produk" required>
                        </div>
                        <div class="col-sm-7 col-lg-7">
                            <input class="form-control" type="text" id="url" name="url" value="{{ old('url') }}" placeholder="URL Video Produk" required>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-sm-2 col-lg-2"></div>
                        <div class="col-sm-10 col-lg-10">
                            <textarea class="form-control" type="text" id="deskripsi" name="deskripsi" placeholder="Deskripsi..." required>{{ old('deskripsi') }}</textarea>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <label for="usulan_dana" class="col-sm-2 col-form-label">Usulan Pendanaan<span style="color: red;"> *</span></label>
                        <div class="col-sm-10 col-lg-10">
                            <div class="input-group">
                                <span class="input-group-text">Rp</span>
                                <input class="form-control" type="text" id="usulan_dana" name="usulan_dana" value="{{ old('usulan_dana') }}" placeholder="Dana yang ingin diajukan (cth: 950000)" required onkeypress="return isNumberKey(event)" onkeyup="formatRupiah(this)">
                            </div>
                            <small id="invalidInput" class="text-danger" style="display: none;">Harap masukkan angka (contoh: 950000)</small>
                            {{-- <small id="dotWarning" style="display: none; color: red;">Simbol titik (.) tidak boleh diinputkan lebih dari 1</small> --}}
                        </div>
                    </div>
                    <div class="mb-0 d-flex justify-content-end">
                        <div>
                            <button type="submit" class="btn btn-primary waves-effect waves-light me-1"> Submit </button>
                            <button type="reset" class="btn btn-secondary waves-effect me-1"> Reset </button>
                            <a href="{{ URL::previous() }}" class="btn btn-danger waves-effect"> Cancel </a>
                        </div>
                    </div>
                {{ Form::close() }}
                <br>
                <h6 class="text-danger">* PASTIKAN FILE PROPOSAL SUDAH BENAR DAN BERFORMAT *.PDF DAN TIDAK LEBIH DARI 5Mb SEBELUM DISUBMIT</h6>
                </div>
            </div>
        </div> <!-- end col -->
    </div> <!-- end row -->

    <!-- Modal -->
<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>
    $(function(){
        $('#input-file').change(function(){
            var input = this;
            var url = window.URL.createObjectURL(this.files[0]);
            $('#view-pdf').attr('src',url);
            $('#view-pdf').attr('height','500px');
        })
    })
</script> --}}

{{-- <script>
    $(function(){
        $('#input-file').change(function(){
            var input = this;
            var url = window.URL.createObjectURL(this.files[0]);
            $('#pdfViewer').attr('src', url);
        });

        // Reset iframe saat modal ditutup
        $('#pdfModal').on('hidden.bs.modal', function (e) {
            $('#pdfViewer').attr('src', '');
        });
    });
</script> --}}

    {{-- <script>
        $(function(){
            $('#btnPreview').click(function() {
                // Ambil URL dari file yang dipilih
                var url = window.URL.createObjectURL($('#input-file')[0].files[0]);
                // Set iframe dengan URL file
                $('#view-pdf').attr('src', url);
                // Munculkan modal
                $('#pdfModal').modal('show');
            });

            // Reset iframe saat modal ditutup
            $('#pdfModal').on('hidden.bs.modal', function (e) {
                $('#view-pdf').attr('src', '');
            });
        });
    </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;
                }

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

            // Reset iframe saat modal ditutup
            $('#pdfModal').on('hidden.bs.modal', function (e) {
                $('#view-pdf').attr('src', '');
            });
        });
    </script>
    <script>
        // Hanya izinkan input angka untuk usulan_dana.
        // Jika ada karakter non-angka (huruf, simbol, spasi, koma, titik, dll),
        // maka akan muncul pesan error #invalidInput dan karakter tersebut dibersihkan.

        // Dipanggil dari atribut onkeypress untuk memblokir sebagian besar input non-angka.
        function isNumberKey(evt) {
            var e = evt || window.event;
            var charCode = e.which ? e.which : e.keyCode;

            // Izinkan tombol kontrol: backspace, tab, enter, esc
            if (charCode === 8 || charCode === 9 || charCode === 13 || charCode === 27) {
                document.getElementById('invalidInput').style.display = 'none';
                return true;
            }

            // Izinkan tombol panah
            if (charCode >= 37 && charCode <= 40) {
                document.getElementById('invalidInput').style.display = 'none';
                return true;
            }

            // Izinkan hanya angka 0–9
            if (charCode >= 48 && charCode <= 57) {
                document.getElementById('invalidInput').style.display = 'none';
                return true;
            }

            // Selain itu dianggap tidak valid
            document.getElementById('invalidInput').style.display = 'block';
            return false;
        }

        // Dipanggil dari onkeyup dan juga di-binding pada event input
        // untuk membersihkan semua karakter non-angka (termasuk hasil paste).
        function formatRupiah(el) {
            if (!el) return;
            var cleaned = (el.value || '').replace(/\D+/g, ''); // hapus semua non-digit
            if (cleaned !== el.value) {
                document.getElementById('invalidInput').style.display = 'block';
            }
            el.value = cleaned;
        }

        // Pastikan validasi juga berjalan saat user melakukan paste atau input lainnya.
        (function () {
            document.addEventListener('DOMContentLoaded', function () {
                var field = document.getElementById('usulan_dana');
                var invalid = document.getElementById('invalidInput');
                if (!field || !invalid) return;

                field.addEventListener('input', function () {
                    var before = field.value;
                    var cleaned = before.replace(/\D+/g, '');
                    field.value = cleaned;
                    if (before !== cleaned) {
                        invalid.style.display = 'block';
                    } else {
                        invalid.style.display = 'none';
                    }
                });
            });
        })();
    </script>

@endsection
