@extends('layouts.master')
@section('page-css')
<link href="https://cdn.jsdelivr.net/npm/summernote@0.9.0/dist/summernote.min.css" rel="stylesheet">
<link rel="stylesheet" href="{{asset('assets/css/formplugins/dropzone/dropzone.css')}}">
@endsection
@section('breadcrumbs')
<ol class="breadcrumb page-breadcrumb">
    @foreach($breadcrumbs as $dataBread)
    <li class="breadcrumb-item {{@$dataBread['active'] == true ? 'active' : ''}}">
        @if(@$dataBread['url'])
        <a href="{{@$dataBread['url']}}">{{$dataBread['name']}}</a>
        @else
        {{$dataBread['name']}}
        @endif
    </li>
    @endforeach
</ol>
@endsection
@section('content')
<div class="row">
    <div class="col-lg-12">
        <div class="card">
            <div class="card-header">
                <i class="fal fa-align-justify"></i> {{$title}}
            </div>
            <form action="{{route($route.'.store')}}" method="POST" enctype="multipart/form-data" id="form">
            {{csrf_field()}}
            <div class="card-body">
                <div class="row">
                    <div class="col-md-12">
                        <input type="hidden" name="secure_id" value="{{@$keyId}}">
                    </div>

                    <div class="col-12 mb-3">
                        <div class="form-group">
                            <label class="col-xl-12 form-label" for="fname">Judul</label>
                            <div class="col-12 pr-1">
                                <input type="text" value="{{@$item->judul ? @$item->judul :  old('judul')}}" name="judul"  class="form-control @error('judul') is-invalid @enderror" placeholder="Masukan Judul" required>
                                @error('judul')
                                <span class="invalid-feedback" style="display: block!important;"><strong>{{$message}}</strong></span>
                                @enderror
                            </div>
                        </div>
                    </div>

                    <div class="col-12 mb-3">
                        <div class="form-group">
                            <label class="col-xl-12 form-label" for="fname">Jenis Kegiatan</label>
                            <div class="col-12 pr-1">
                                <select required class="form-control @error('kategori') is-invalid @enderror" name="kategori" id="">
                                    <option value="">-- PILIH JENIS KEGIATAN --</option>
                                    <option {{ @$item->kategori == 'Kota' ? 'selected' : '' }} value="Kota">Kegiatan Kota</option>
                                    <option {{ @$item->kategori == 'Provinsi' ? 'selected' : '' }} value="Provinsi">Kegiatan Provinsi</option>
                                    <option {{ @$item->kategori == 'Nasional' ? 'selected' : '' }} value="Nasional">Kegiatan Nasional</option>
                                    <option {{ @$item->kategori == 'Mandiri' ? 'selected' : '' }} value="Mandiri">Kegiatan Mandiri</option>
                                </select>
                                @error('kategori')
                                    <span class="invalid-feedback" style="display: block!important;"><strong>{{$message}}</strong></span>
                                @enderror
                            </div>
                        </div>
                    </div>

                    <div class="col-12 mb-3">
                        <div class="form-group">
                            <label class="col-xl-12 form-label" for="fname">Deskripsi</label>
                            <div class="col-12 pr-1">
                                <textarea name="body" id="summernote"  class="form-control @error('body') is-invalid @enderror" cols="30" rows="10" required>{{@$item->body ? @$item->body :  old('body')}}</textarea>
                                @error('body')
                                <span class="invalid-feedback" style="display: block!important;"><strong>{{$message}}</strong></span>
                                @enderror
                            </div>
                        </div>
                    </div>

                    <div class="col-12 mb-3">
                        <div class="form-group">
                            <label class="col-xl-12 form-label" for="fname">Image</label>
                            <div class="col-12 pr-1">
                                {{-- <input type="file" accept=".png,.jpg,.jpeg" name="image"  class="form-control @error('image') is-invalid @enderror"> --}}
                                <div style="border: 2px dashed #0087F7; padding: 20px;" class="dropzone" id="my-dropzone">
                                    <div class="dz-message">
                                        Drop PDF files here or click to upload
                                    </div>
                                </div>
                                <div id="uploaded-files" style="margin-top: 20px; display:none;">
                                    <ul id="file-list">
                                    </ul>
                                </div>
                                @error('image')
                                <span class="invalid-feedback" style="display: block!important;"><strong>{{$message}}</strong></span>
                                @enderror
                            </div>
                        </div>
                    </div>

                    @if(@$item->image)
                        <?php
                            $image = json_decode($item->image);
                        ?>
                        <div class="col-12 mb-3">
                            <div class="form-group">
                                <div class="col-12 pr-1">
                                    <div class="row mb-2">
                                        @foreach($image as $img)
                                        <div class="col-3">
                                            <img src="{{ asset($img) }}" alt="" class="img-fluid">
                                            <a href="#" data-url="{{ $img }}" data-href="{{ route($route.'.image.delete',encode_id($item->KegiatanId)) }}" class="btn btn-danger btnDeleteImage mt-1 btn-block">Hapus</a>
                                        </div>
                                        @endforeach
                                    </div>
                                </div>
                            </div>
                        </div>
                    @endif

                </div>
            </div>
            <div class="card-footer">
                <div class="row">
                    <div class="col-md-12 text-right">
                        <a href="{{route($route.'.index')}}" class="btn btn-danger"><i class="fal fa-times"></i> Batal</a>
                        <button type="submit" class="btn btn-success"><i class="fal fa-save"></i> Simpan</button>
                    </div>
                </div>
            </div>
            </form>
        </div>
    </div>
</div>
@endsection
@section('page-js')
<!-- include summernote css/js -->
    <script src="https://cdn.jsdelivr.net/npm/summernote@0.9.0/dist/summernote.min.js"></script>
    <script type="text/javascript" src="{{asset('assets/js/formplugins/dropzone/dropzone.js')}}"></script>
	<script type="text/javascript">
    $(document).ready(function() {
        $('#summernote').summernote();
    });
    $('.btnDeleteImage').on('click',function(){
        var base_url = $(this).attr('data-href');
        var url = $(this).attr('data-url');
            swal({
                title: "Hapus Data!",
                text: "Apa anda yakin ingin menghapus data ini ?",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "Ya Hapus Sekarang",
                cancelButtonText: "Tidak",
                closeOnConfirm: true,
                closeOnCancel: true
            },
            function(isConfirm) {
                if(isConfirm){
                
                request = $.ajax({
                    url: base_url,
                    xhrFields: {
                        withCredentials: true
                    },
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    data:{
                        url:url
                    },
                    type: "POST",
                });

                // Callback handler that will be called on success
                request.done(function(response, textStatus, jqXHR){
                    console.log(response);
                    toastr.success("Berhasil Menhapus Data", 'Berhasil!', {positionClass: 'toast-bottom-right', containerId: 'toast-bottom-right'});
                    setInterval(window.location.reload(), 5000);
                });

                // Callback handler that will be called on failure
                request.fail(function (jqXHR, textStatus, errorThrown){
                    toastr.error(
                        "Gagal "+textStatus, errorThrown
                    );
                });
                }
            }); 
            return false;
    });
     $(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
            }
        });
    });   

        const myDropzone = new Dropzone(".dropzone", {
                url: "{{ url('uploadTempImage') }}", // URL ke controller kamu
                method: "POST",
                // xhrFields: {
                //     withCredentials: true
                // },
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'X-Requested-With': 'XMLHttpRequest'
                },
                // maxFilesize: 1, // dalam MB
                acceptedFiles: ".png,.jpg,.jpeg",
                paramName: "file", // nama input file yang dikirim ke controller
                params: {
                    _token: document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                },
                uploadMultiple: true,
                init: function() {
                    this.on("successmultiple", function(files, response) {
                        console.log('Upload success multiple:', response);

                        const fileList = document.getElementById('file-list');

                        response.files.forEach(function(fileInfo) {
                            const li = document.createElement('li');
                            li.innerHTML = `<a>${fileInfo.filename}</a>`;
                            fileList.appendChild(li);

                            // Tambahkan ke hidden input kalau perlu
                            const hiddenInput = document.createElement('input');
                            hiddenInput.type = 'hidden';
                            hiddenInput.name = 'input_upload_files[]';
                            hiddenInput.class = 'removeFormKriteria';
                            hiddenInput.value = fileInfo.filename;
                            var elem = '<input type="hidden" name="input_upload_files[]" value="'+fileInfo.filename+'" class="removeFormKriteria uploadedFiles is-required">';
                            $('#form').append(elem);
                        });
                    });

                    this.on("error", function(file, response) {
                        console.error('Upload error:', response);
                        toastr.error(response, 'Error!', {positionClass: 'toast-bottom-right', containerId: 'toast-bottom-right'});
                        this.removeFile(file);
                    });
                }
            });
    </script>
@endsection