@extends('layouts.master')

@section('page-css')
<link rel="stylesheet" media="screen, print" href="{{asset('assets/css/datagrid/datatables/datatables.bundle.css')}}">
<link rel="stylesheet" href="{{asset('assets/css/formplugins/dropzone/dropzone.css')}}">
@endsection
@section('content')
<form method="POST" id="form" enctype="multipart/form-data">
        {{csrf_field()}}
        <input type="hidden" name="secure_id" value="{{encode_id($kuesioner->KuesionerId)}}">
<div class="row">
    <div class="col-12 mb-3">
        <div class="d-flex flex-row justify-content-between">
            <div class="d-flex align-items-center">
                <div class="subheader mb-0">
                    <h1 class="subheader-title">
                        {{$title}}
                    </h1>
                </div>
            </div>
            <div class="align-items-end">
                <div class="card">
                    <div class="card-body p-2">
                        <div class="d-flex flex-row gap-3 justify-content-center align-items-center">
                            <div class="p-2 bg-secondary rounded">
                                <i class="fal fa-home"></i>
                            </div>
                            <div>
                                <h5 class="fw-700 mb-1">{{session('name')}}</h5>
                                <p class="mb-0">NPSN: {{session('npsn')}}</p>
                            </div>
                            <div class="d-flex flex-column gap-1">
                                <span class="badge bg-primary-light text-primary">{{session('tingkat_sekolah')}}</span>
                                <span class="badge bg-success-light text-success">{{session('status_sekolah')}}</span>
                                <span class="badge bg-info-light text-info">Level {{levelAdiwiyata(session('npsn'))}}</span>
                            </div>
                        </div>  
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-12">
        @if ($errors->any())
            <div class="alert alert-danger">
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif
    </div>
    @if(($kuesioner->status == 1) || ($kuesioner->status == 5))
    <div class="col-lg-12">
        <div class="alert alert-warning">
            <p class="mb-0"><i class="fal fa-info-circle"></i>&nbsp;Anda Belum Melakukan Finalisasi Proses Data Kriteria</p>
            <p class="mb-0"><i class="fal fa-info-circle"></i>&nbsp;Klik <b class="text-danger">Progress Usulan</b> untuk melakukan Finalisasi Proses Data Kriteria</p>
        </div>
    </div>
    @endif
    
        <div class="col-md-4">
            <div class="card">
                <div class="card-body">
                    <div class="pageNumber row gap-1 justify-content-center">
                        @foreach($page as $hal)
                            <div class="col-3 text-center page {{ checkPenilaian($hal,null,null,$kuesioner->KuesionerId)}}" data-number={{$hal}}>
                                <span>
                                    {!! checkCatatan($hal,null,null,$kuesioner->KuesionerId) !!}
                                    {{$hal}}
                                </span>
                            </div>
                        @endforeach
                    </div>
                    <div class="row mt-2 gap-1 justify-content-center">
                        <div class="col-5 d-none text-center resume border-secondary rounded" style="padding: 10px;">
                            <span>Resume</span>
                        </div>
                        <div class="col-5 text-center progress_usulan border-secondary rounded" style="padding: 10px;">
                            <span>Progress Usulan</span>
                        </div>
                    </div>
                    <hr>
                    <div class="row mt-2 gap-1 justify-content-center align-items-center">
                        <i class="fal fa-info-circle"></i> : Terdapat Catatan Dari Penilai
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-8">
            <div class="row">
                <div class="col-md-12">
                    <div class="alert alert-primary mb-2 p-2">
                        <h6 class="mb-0"><b class="changeTitle">I. Kebijakan</b></h6>
                    </div>
                </div>
                <div class="col-md-12 bodyInput">
                    <div id="loading-spinner" style="display: none; text-align: center;">
                        <img src="{{ asset('assets/spinner.gif') }}" alt="Loading..." width="20">
                    </div>
                    <div class="changeForm">
                        {!! formKriteria(1,null,null,tahunKuesioner($kuesioner->KuesionerId)) !!}
                    </div>
                </div>
                <div class="col-md-12">
                    @if(session('group_alias') == 'sekolah')
                        @if(($kuesioner->status == 1) || ($kuesioner->status == 5))
                            <div class="text-right">
                                <button id="btnSave" class="btn btn-success"><i class="fal fa-save"></i>&nbsp;Simpan Data</button>
                            </div>
                        @endif
                    @endif
                </div>
            </div>
        </div>
    </div>
</form>
@endsection
@section('page-js')
<script type="text/javascript" src="{{asset('assets/js/formplugins/dropzone/dropzone.js')}}"></script>
<script type="text/javascript">
    @if(session('group_alias') == 'sekolah')
        @if(($kuesioner->status != 1) && ($kuesioner->status != 5))
            $('.dropzone').remove();
        @endif
    @endif
    // $('.dropzone').on('click',function(){
        // Dropzone.autoDiscover = false; // Penting supaya tidak auto-initialize!
    // const myDropzone = new Dropzone(".dropzone", {
    //             url: "{{ url('uploadTemp') }}", // URL ke controller kamu
    //             method: "POST",
    //             headers: {
    //                 'X-CSRF-TOKEN': "{{csrf_token()}}"
    //             },
    //             xhrFields: {
    //                 withCredentials: true
    //             },
    //             // maxFilesize: 1, // dalam MB
    //             acceptedFiles: ".pdf",
    //             paramName: "file", // nama input file yang dikirim ke controller
    //             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.value = fileInfo.filename;
    //                         hiddenInput.class = 'removeFormKriteria';
    //                         var elem = '<input type="hidden" name="input_upload_files[]" value="'+fileInfo.filename+'" class="removeFormKriteria uploadedFiles is-required">';
    //                         $('.changeForm').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>

<script type="text/javascript">
    $(document).on('change', '.uncheckall', function () {
        if ($(this).is(':checked')) {
            // uncheck semua checkbox KECUALI checkbox terakhir ini
            $('.checklistInput').not(this).prop('checked', false);
            $('.file-item').addClass('d-none');
            $('.file-itemInput').removeClass('is-required');
        }
    });

    $(document).on('change', '.checklistInput:not(.uncheckall)', function () {
        if ($(this).is(':checked')) {
            // kalau checkbox biasa dicentang, pastikan checkbox uncheckall mati
            $('.uncheckall').prop('checked', false);
        }
    });

    $(document).on('change', '.checklistInput[type="radio"]', function () {
        const value = $(this).data('value');
        const label = $(this).val();
        const container = $('#dynamic-file-container');

        // Radio hanya 1 → hapus semua dulu
        container.empty();

        container.append(`
            <div class="mb-3 file-item" id="file_${value}">
                <label class="fw-500">Upload Dokumen ${label}</label>
                <input type="hidden" name="input_upload_files_label[]" value="${value}">
                <input type="file" accept=".pdf,.png,.jpeg,.jpg" name="input_upload_files" class="removeFormKriteria is-required form-control">
                <span class="text-danger"><i>Ukuran Maksimal File : 10MB, Ekstension File : .pdf,.png,.jpeg,.jpg</i></span>
            </div>
        `);
    });

    $(document).on('change', '.checklistInput', function () {
        const value = $(this).data('value');
        const label = $(this).val();
        const container = $('#dynamic-file-container');

        if ($(this).is(':checked')) {

            $('.'+value).removeClass('d-none');
            $('.'+value+'Class').addClass('is-required');

            // Cegah double insert
            // if ($('#file_' + value).length === 0) {
            //     container.append(`
            //         <div class="mb-3 file-item" id="file_${value}">
            //             <label class="fw-500">Upload Dokumen ${label}</label>
            //             <input type="hidden" name="input_upload_files_label[]" value="${value}">
            //             <input type="file" accept=".pdf,.png,.jpeg,.jpg" name="input_upload_files[]" class="removeFormKriteria is-required form-control">
            //             <span><i>Ukuran Maksimal File : 10MB, Ekstension File : .pdf,.png,.jpeg,.jpg</i></span> 
            //         </div>
            //     `);
            // }

        } else {
            $('.'+value).addClass('d-none');
            $('.'+value+'Class').removeClass('is-required');
            // $('#file_' + value).remove();
        }
    });

    function getForm(number){
        let base_url = "{{url('/')}}";
        $.ajax({
            url: base_url+'/getForm', // Ganti dengan URL API-mu
            type: 'POST', // Bisa juga 'POST' kalau perlu
            xhrFields: {
                withCredentials: true
            },
            data: { 
                _token:'{{csrf_token()}}',
                page: number,
                kuesionerId: '{{ $kuesioner->KuesionerId }}' 
            }, // Kirim number sebagai parameter
            dataType: 'json', // Format respons JSON
            beforeSend: function () {
                $('#loading-spinner').show(); // Menampilkan spinner
                $('.removeFormKriteria').remove();
            },
            success: function (response) {
                // console.log('Response:', response);
                $('.changeForm').append(response.data);
                $('.changeTitle').html(response.title);

                $('.numberInput').on('input', function() {
                    this.value = this.value.replace(/[^0-9]/g, ''); // Hanya angka 0-9
                });

                $('.btnDeletFile').on('click',function(){
                    var base_url = $(this).attr('data-href');
                    var id = $(this).attr('data-id');
                    swal({
                        title: "Hapus File!",
                        text: "Apa anda yakin ingin hapus Dokumen ini ?",
                        type: "warning",
                        showCancelButton: true,
                        confirmButtonColor: "#BF3131",
                        confirmButtonText: "Hapus Sekarang",
                        cancelButtonText: "Batal",
                        closeOnConfirm: true,
                        closeOnCancel: true
                    },
                    function(isConfirm) {
                        if(isConfirm){
                        
                        request = $.ajax({
                            url: base_url,
                            xhrFields: {
                                    withCredentials: true
                                },
                            type: "GET",
                        });

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

                        // Callback handler that will be called on failure
                        request.fail(function (jqXHR, textStatus, errorThrown){
                            toastr.error(
                                "Gagal "+textStatus, errorThrown
                            );
                        });
                        }
                    }); 
                    return false;
            });
            },
            error: function (xhr, status, error) {
                console.error('AJAX Error:', status, error);
                alert('Failed to fetch data!');
            },
            complete: function () {
                $('#loading-spinner').hide(); // Sembunyikan spinner setelah request selesai
            }
        }); 
    }

   $('.page').on('click',function(e){
        e.preventDefault();
        let number = $(this).data('number');
        
        // Tambahkan kelas active dan hapus dari yang lain
        $('.page').removeClass('bg-primary-light border-primary text-primary');
        $(this).addClass('bg-primary-light border-primary text-primary');

        getForm(number);
               
   });

   $('.resume').on('click',function(e){
        window.location.href = "{{url('usulan/adiwiyata/kriteria/resume/'.encode_id(session('sekolah_id')))}}";
   });

   $('.progress_usulan').on('click',function(e){
        window.location.href = "{{url('usulan/adiwiyata/kriteria/progress/'.encode_id(session('sekolah_id')))}}";
   });
   
   $('.btnDeletFile').on('click',function(){
        var base_url = $(this).attr('data-href');
        var id = $(this).attr('data-id');
        swal({
             title: "Hapus File!",
             text: "Apa anda yakin ingin hapus Dokumen ini ?",
             type: "warning",
             showCancelButton: true,
             confirmButtonColor: "#BF3131",
             confirmButtonText: "Hapus Sekarang",
             cancelButtonText: "Batal",
             closeOnConfirm: true,
             closeOnCancel: true
         },
         function(isConfirm) {
            if(isConfirm){
              
              request = $.ajax({
                  url: base_url,
                  xhrFields: {
                        withCredentials: true
                    },
                  type: "GET",
              });

              // Callback handler that will be called on success
              request.done(function(response, textStatus, jqXHR){
                alert(response.page);
                  console.log(response);
                  getForm(response.page);
                  toastr.success("Berhasil Update Data", 'Berhasil!', {positionClass: 'toast-bottom-right', containerId: 'toast-bottom-right'});
              });

              // Callback handler that will be called on failure
              request.fail(function (jqXHR, textStatus, errorThrown){
                  toastr.error(
                      "Gagal "+textStatus, errorThrown
                  );
              });
            }
         }); 
        return false;
   });

   $('#btnSave').on('click', function (e) {
        e.preventDefault();

        let isValid = true;
        let isMultiple = true;

        // =========================
        // VALIDASI FIELD REQUIRED
        // =========================
        $('.is-required').each(function () {
            let type = $(this).attr('type');
            let name = $(this).attr('name');
            let value = $(this).val()?.trim();

            if (type === 'radio') {
                if ($(`input[name="${name}"]:checked`).length === 0) {
                    isValid = false;
                    $(`input[name="${name}"]`).addClass("is-invalid");
                } else {
                    $(`input[name="${name}"]`).removeClass("is-invalid");
                }

            } else if (type === 'checkbox') {
                let checkedCount = $(`input[name="${name}"]:checked`).length;

                if (checkedCount === 0) {
                    isValid = false;
                    $(`input[name="${name}"]`).addClass("is-invalid");
                } else if (checkedCount === 1) {
                    isMultiple = false;
                    $(`input[name="${name}"]`).addClass("is-invalid");
                } else {
                    $(`input[name="${name}"]`).removeClass("is-invalid");
                }

            } else if (type === 'file') {
                if (this.files.length === 0) {
                    isValid = false;
                    $(this).addClass("is-invalid");
                } else {
                    $(this).removeClass("is-invalid");
                }

            } else {
                if (!value) {
                    isValid = false;
                    $(this).addClass("is-invalid");
                } else {
                    $(this).removeClass("is-invalid");
                }
            }
        });

        if (!isValid) {
            toastr.error(
                "Harap isi semua field yang wajib diisi",
                "Error!",
                { positionClass: 'toast-bottom-right' }
            );
            return;
        }

        // =========================
        // FORM DATA (AUTO FILE + INPUT)
        // =========================
        let formElement = document.getElementById('form');
        let number = $('.page').data('number');
        let formData = new FormData(formElement);

        let replaceIndex = $('input[type="file"][data-replace-index]').data('replace-index');

        if (replaceIndex !== undefined) {
            formData.append('replace_index', replaceIndex);
        }

        // OPTIONAL: debug isi FormData
        /*
        for (let pair of formData.entries()) {
            console.log(pair[0]+ ':', pair[1]);
        }
        */

        // =========================
        // AJAX SUBMIT
        // =========================
        $.ajax({
            url: "{{ route($route.'.store') }}",
            type: "POST",
            xhrFields: {
                withCredentials: true
            },
            data: formData,
            processData: false, // WAJIB
            contentType: false, // WAJIB
            beforeSend: function () {
                $('#loading-spinner').show();
            },
            success: function (response) {
                toastr.success(
                    "Berhasil menyimpan data",
                    "Success!",
                    { positionClass: 'toast-bottom-right' }
                );

                $('.page')
                    .closest('.bg-primary-light')
                    .addClass('bg-success-light border-success text-success')
                    .removeClass('bg-primary-light border-primary border-secondary text-primary');

                    getForm(response.page_number);
            },
            error: function (xhr) {
                toastr.error(
                    "Maaf terjadi kesalahan saat menyimpan data",
                    "Error!",
                    { positionClass: 'toast-bottom-right' }
                );
            },
            complete: function () {
                $('#loading-spinner').hide();
            }
        });
    });


   $('#btnSave1').on('click',function(e){
        e.preventDefault();
        let currentForm = $("#form").serializeArray();
        // console.log(currentForm);

        let formData = {};
        let allData = {};
        let isValid = true; // Flag validasi
        let isMultiple = true; // Flag validasi
        let file = $('#file-list').attr('data-file');

        currentForm.forEach(field => {
            let name = field.name.replace(/\[\]$/, ''); // Hapus "[]" di akhir nama input

            if (allData[name]) {
                if (!Array.isArray(allData[name])) {
                    allData[name] = [allData[name]];
                }
                allData[name].push(field.value);
            } else {
                allData[name] = field.value;
            }
        });

        // alert(file);

        $('.is-required').each(function () {
            let type = $(this).attr('type');
            let name = $(this).attr('name');
            let value = $(this).val()?.trim(); // Pastikan nilai di-trim untuk menghindari spasi kosong

            let uploadedFilesValue = $('.uploadedFiles').val();
            // if(file == 'false'){
            //     if (!uploadedFilesValue || uploadedFilesValue === '') {
            //         isValid = false;
            //         $('.uploadedFiles').addClass("is-invalid");
            //         toastr.error("Harap upload minimal 1 file", 'Error!', {positionClass: 'toast-bottom-right'});
            //         return;
            //     } else {
            //         $('.uploadedFiles').removeClass("is-invalid");
            //     }
            // }

            if (type === 'radio') {
                // Validasi radio: setidaknya satu opsi harus dipilih
                if ($(`input[name="${name}"]:checked`).length === 0) {
                    isValid = false;
                    $(`input[name="${name}"]`).closest('.custom-control-input').addClass("is-invalid");
                } else {
                    $(`input[name="${name}"]`).closest('.custom-control-input').removeClass("is-invalid");
                }
            }else if(type === 'checkbox'){
                if ($(`input[name="${name}"]:checked`).length === 0) {
                    isValid = false;
                    $(`input[name="${name}"]`).closest('.custom-control-input').addClass("is-invalid");
                }else if ($(`input[name="${name}"]:checked`).length === 1) {
                    isMultiple = false;
                    $(`input[name="${name}"]`).closest('.custom-control-input').addClass("is-invalid");
                } else {
                    $(`input[name="${name}"]`).closest('.custom-control-input').removeClass("is-invalid");
                }
            } else {
                // Validasi input teks atau lainnya
                if (!value) {
                    isValid = false;
                    $(this).addClass("is-invalid");
                } else {
                    $(this).removeClass("is-invalid");
                }
            }
        });

        // Jika validasi gagal, hentikan submit
        if (!isValid) {
            toastr.error("Harap isi semua field yang wajib diisi", 'Error!', {positionClass: 'toast-bottom-right', containerId: 'toast-bottom-right'});
            // alert(".");
            return;
        }
        
        // if (!isMultiple) {
        //     toastr.error("Harap isi minimal lebih dari 1 isian", 'Error!', {positionClass: 'toast-bottom-right', containerId: 'toast-bottom-right'});
        //     // alert(".");
        //     return;
        // }

        $.ajax({
            url: "{{route($route.'.store')}}", // Ganti dengan URL API-mu
            type: 'POST', // Bisa juga 'POST' kalau perlu
            xhrFields: {
                withCredentials: true
            },
            data: { 
                _token:'{{csrf_token()}}',
                data: allData 
            }, // Kirim number sebagai parameter
            dataType: 'json', // Format respons JSON
            beforeSend: function () {
                $('#loading-spinner').show(); // Menampilkan spinner
            },
            success: function (response) {
                // console.log('Response:', response);
                toastr.success("Berhasil menyimpan data", 'Success!', {positionClass: 'toast-bottom-right', containerId: 'toast-bottom-right'});

                
                // $('.page').closest('.active').addClass('bg-success');
                // $('.page').closest('.active').addClass('text-white');

                $('.page').closest('.bg-primary-light').addClass('bg-success-light border-success text-success');
                $('.page').closest('.bg-primary-light').removeClass('bg-primary-light border-primary border-secondary text-primary');

                // $('.page').removeClass('active');
                // (checkPenilaian($hal) == true ? 'bg-success text-white' : '' )
            },
            error: function (xhr, status, error) {
                // console.error('AJAX Error:', status, error);
                // alert('Failed to fetch data!');
                toastr.error("Maaf Terjadi Kesalahan Menyimpan Data", 'Error!', {positionClass: 'toast-bottom-right', containerId: 'toast-bottom-right'});
            },
            complete: function () {
                $('#loading-spinner').hide(); // Sembunyikan spinner setelah request selesai
            }
        });

   });
</script>
@endsection