@extends('layouts.master')
@section('content')
<div class="flex-1 overflow-y-auto p-8 custom-scrollbar">
    <div class="p-8 bg-white rounded-3xl border border-slate-200 shadow-sm overflow-hidden">
        <form action="{{route($route.'.store')}}" method="POST" class="" enctype="multipart/form-data">
            {{csrf_field()}}
            <input type="hidden" name="secure_id" value="{{@$keyId}}">
            <div class="flex flex-col p-3 gap-3">
                <h5 class="text-lg text-slate-700 font-bold">Informasi Instansi</h5>
                <hr>
                <div class="flex gap-4 mt-5">
                    <label class="mb-3 w-1/2 font-semibold required">Instansi</label>
                    <select name="instansi_id" {{ @$item ? 'disabled' : 'required' }} class="p-2 bg-white rounded border instansi_id select2 @error('instansi_id') is-invalid @enderror" id="instansi_id">
                        <option value="">-</option>
                        @foreach($instansi as $dataInstansi)
                        <option {{@$item->instansi_id == $dataInstansi->MsInstansiId ? 'selected' : ''}} value="{{encode_id($dataInstansi->MsInstansiId)}}">{{$dataInstansi->name}}</option>
                        @endforeach
                    </select>
                    @error('instansi_id')
                    <span class="invalid-feedback" style="display: block!important;"><strong>{{$message}}</strong></span>
                    @enderror
                </div>
                <div class="flex gap-4">
                    <label class="mb-3 w-1/2 font-semibold required">Sumber Data</label>
                    <div class="flex flex-col w-full justify-center items-start gap-2">
                        <select name="template_id" {{ @$item ? 'disabled' : 'required' }} class="p-2 bg-white rounded border template_id select2 @error('template_id') is-invalid @enderror" id="template_id">
                            @if(@$item)
                            <option value="">Tabel {{@$item->tabelData->nomor_tabel}} - {{@$item->tabelData->name}}</option>
                            @else
                            <option value="">-- Pilih Sumber Data --</option>
                            @endif
                            
                        </select>
                        <a href="{{ url('opendata/dataset/generateTemplate/'.encode_id(@$item->ms_tabel_data_id)); }}" class="p-2 bg-emerald-500 btnDownload text-white rounded flex gap-2 items-center"><i data-lucide="download" class="w-4 h-4 mr-2"></i><span>Download Template Excel</span></a>
                    </div>
                    
                    @error('template_id')
                    <span class="invalid-feedback" style="display: block!important;"><strong>{{$message}}</strong></span>
                    @enderror
                </div>
                <h5 class="text-lg text-slate-700 font-bold">Informasi Dataset</h5>
                <hr>
                <div class="flex gap-4 mt-4">
                    <label class="mb-3 w-1/2 font-semibold required">Nama Dataset</label>
                    <div class="flex flex-col w-full justify-center items-start gap-2">
                        <input type="text" readonly value="{{@$item->name ? @$item->name :  old('name')}}" name="name" class="p-2 w-full bg-gray-200 rounded border nama_dataset @error('name') is-invalid @enderror" placeholder="Masukan Nama Dataset" required>
                    </div>
                    @error('name')
                    <span class="invalid-feedback" style="display: block!important;"><strong>{{$message}}</strong></span>
                    @enderror
                </div>
                <div class="flex gap-4">
                    <label class="mb-3 w-1/2 font-semibold {{ @$item ? '' : 'required' }} ">Unggah Berkas</label>
                    <div class="flex flex-col w-full justify-center items-start gap-2">
                        <input type="file" accept=".xls,.xlsx" value="{{@$item->file ? @$item->file :  old('file')}}" name="file" class="p-2 w-full bg-white rounded border @error('file') is-invalid @enderror" placeholder="Masukan File Dataset" {{ @$item ? '' : 'required' }} >
                        <small><i>Masukan Ekstensi File : .xls,.xlsx</i></small>
                        <div class="p-2 bg-blue-100 flex justify-center items-center text-blue-600 rounded">
                            <i data-lucide="info" class="w-4 h-4 mr-2"></i> <p>Pastikan file template di save as ke format <b>Excel 94-2004 / 2003 .xls</b></p>
                        </div>
                        @if(@$item)
                            <a href="{{url('opendata/dataset/download/'.encode_id(@$item->DatasetId))}}" class="p-2 bg-blue-500 rounded text-white flex items-center"><i data-lucide="download" class="w-4 h-4 mr-2"></i>Download File</a>
                        @endif
                    </div>
                    @error('file')
                    <span class="invalid-feedback" style="display: block!important;"><strong>{{$message}}</strong></span>
                    @enderror
                </div>

                <div class="flex gap-4">
                    <label class="mb-3 w-1/2 font-semibold required">Deskripsi Dataset</label>
                    <textarea name="deskripsi" rows="10" required class="p-2 bg-white w-full rounded border @error('deskripsi') is-invalid @enderror" id="">{{@$item->deskripsi}}</textarea>
                    @error('deskripsi')
                    <span class="invalid-feedback" style="display: block!important;"><strong>{{$message}}</strong></span>
                    @enderror
                </div>
                <div class="flex gap-4">
                    <label class="mb-3 w-1/2 font-semibold">Tahun Sistem SLHD</label>
                    <select name="tahun" class="p-2 bg-gray-200 read-only rounded border w-full" id="">
                        <option value="{{@$item->tahun ? @$item->tahun : date('Y')}}">{{@$item->tahun ? @$item->tahun : date('Y')}}</option>
                        {{-- @for($i = (date('Y')-5); date('Y') >= $i ;  $i++)
                        <option {{ (@$item ? (@$item->tahun == $i ? 'selected' : '') : ($i == date('Y') ? 'selected' : '') )}} value="{{$i}}">{{$i}}</option>
                        @endfor --}}
                    </select>
                </div>
                <div class="flex gap-4">
                    <label class="mb-3 w-1/2 font-semibold">Tahun Data</label>
                    <select name="tahun_data" class="p-2 bg-white rounded border w-full" id="">
                        @for($i = (date('Y')-2); date('Y')-1 >= $i ;  $i++)
                            <option {{ (@$item ? (@$item->tahun_data == $i ? 'selected' : '') : ($i == date('Y')-1 ? 'selected' : '') )}} value="{{$i}}">{{$i}}</option>
                        @endfor
                    </select>
                </div>

            </div>
            @if((@$item->status == 0) || (@$item->status == 2) || (session('group_id') == 1) || (session('group_alias') == 'admin') || (session('group_alias') == 'admin_ta'))
                <div class="flex justify-center items-center gap-2">
                    <a href="{{route($route.'.index')}}" class="bg-red-500 rounded py-2 px-3 text-white flex items-center"><i data-lucide="arrow-left" class="w-4 h-4 mr-2"></i><span>Batal</span></a>
                    <button type="submit" class="bg-emerald-500 rounded py-2 px-3 text-white flex items-center"><i data-lucide="save" class="w-4 h-4 mr-2"></i><span> <span>Simpan</span></button>
                </div>
            @endif
            
        </form>
    </div>
</div>
@endsection
@section('js')
    <script>
        function clear(elementId) {
            $('#' + elementId).empty();
            $('#' + elementId).select2();
        }
        $('select').on("select2:selecting", function(e) {
            var selectorOrigin = this.id;
            var id = e.params.args.data.id;
            
            
            if(selectorOrigin=='instansi_id'){
                $('#loading-spinner').show();
                clear('template_id');
                selector = 'template_id';
                url_to = 'getResourceData';
                getSelect(id, selector, url_to);
            }
        });

        function getSelect(id, selectTo, urlTo, selected = "") {
            id = id;
            var base_url = "{{url('/')}}";
            //alert(id);
            destino = "#" + selectTo;
            console.log(id);
            valor = $('#' + id).find(":selected").val();

            $.ajax({
                method: "GET",
                url: base_url + '/' + urlTo,
                data: {
                    id: id
                }
            })
            .done(function(msg) {
                obj = msg.data;

                if (obj.length > 0) {
                //Clear the current options
                $(destino).empty();
                
                if(selectTo=='template_id'){
                    $(destino).append('<option value="">-PILIH Sumber Data-</option>').select2("val", "0");
                    
                    $.each(obj, function(index) {
                        value = obj[index].id;
                        text = obj[index].name;
                        text2 = obj[index].name2;
                        excel = obj[index].excel;
                        $(destino).append('<option data-name="'+text2+'" data-template="'+excel+'" value=' + value + '>' + text + '</option>');
                    });
                    console.log(selected)
                    if (selected) {
                        $(destino).val(selected).trigger('change');
                        selected = "";
                    }
                }

                
                } else {
                    if(selectTo=='template_id'){
                        $(destino).empty().append('<option value="0">-PILIH Sumber Data-</option>').select2("val", "0");
                    }
                }
                $('#loading-spinner').hide();
            });
            return false;
        }
    </script>
    <script>
        
        const input = document.getElementById('tag-input');
        const container = document.getElementById('tag-container');

        input.addEventListener('keydown', function (e) {
            if (e.key === 'Enter' && this.value.trim() !== '') {
            e.preventDefault();
            const tagText = this.value.trim();

            // Buat tag baru
            const tag = document.createElement('span');
            tag.className = 'inline-flex items-center px-2 py-1 bg-primary text-white text-sm rounded';
            tag.innerHTML = `${tagText} <button type="button" class="ml-1 text-blue-500 hover:text-red-600">&times;</button>`;

            // Hidden input untuk dikirim ke server
                const hiddenInput = document.createElement('input');
                hiddenInput.type = 'hidden';
                hiddenInput.name = 'tags[]';
                hiddenInput.value = tagText;
            
            // Tempelkan ke tag
            tag.appendChild(hiddenInput);

            // Tambahkan tag ke container sebelum input
            container.insertBefore(tag, input);

            // Reset input
            this.value = '';

            // Hapus tag saat tombol × ditekan
            tag.querySelector('button').addEventListener('click', () => tag.remove());
            }
        });
        </script>
	<script type="text/javascript">
        $('.template_id').on('change',function(){
            var template = $(this).find(':selected').attr('data-template');
            var name = $(this).find(':selected').attr('data-name');
            $('.btnDownload').attr('href',template);
            $('.nama_dataset').val(name);
        });

        $('#template_default').on('change',function(){
            var instansi_id = $('.instansi_id').find(':selected').val();
            var val = $(this).find(':selected').val();
            var template = $('.template_id').find(':selected').attr('data-template');
            if(instansi_id == ''){
                toastr.error("Data instansi_id Belum Dipilih", 'Error!', {positionClass: 'toast-bottom-right', containerId: 'toast-bottom-right'});
                $('#template_default').val('');
            }else{
                if(val == 1){
                    $('.btnDownload').attr('href',template);
                    $('.btnDownload').removeClass('hidden');
                }else{
                    $('.btnDownload').attr('href',"#");
                    $('.btnDownload').addClass('hidden');
                }
            }
        });
        $(document).ready(function() {
            $('.numberInput').on('input', function() {
                this.value = this.value.replace(/[^0-9]/g, ''); // Hanya angka 0-9
            });
            $('#togglePassword').on('click', function() {
                let passwordField = $('#password');
                let icon = $(this).find('i');

                // Cek apakah input saat ini bertipe password
                if (passwordField.attr('type') === 'password') {
                    passwordField.attr('type', 'text'); // Ubah ke teks
                    icon.removeClass('fa-eye').addClass('fa-eye-slash'); // Ganti ikon
                } else {
                    passwordField.attr('type', 'password'); // Ubah ke password
                    icon.removeClass('fa-eye-slash').addClass('fa-eye'); // Kembalikan ikon
                }
            });
        });   
    </script>
@endsection