@extends('layouts.master')

@section('page-css')
@endsection
@section('content')
<div class="row" id="accordion">
    <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-md-12">
        <div class="alert alert-warning mb-2">
            <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>
    @if ($errors->any())
        <div class="col-md-12">
            <div class="alert alert-danger mb-2">
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        </div>
    @endif

        
        @foreach($page as $k => $dataNumber)
        <div class="col-lg-12 mb-2">
            <div class="card mb-2">
                <div class="card-header bg-primary-light py-1 px-0" id="heading{{$k}}">
                    <h5 class="mb-0">
                      <button class="btn btn-link" data-toggle="collapse" data-target="#collapse{{$k}}" aria-expanded="true" aria-controls="collapse{{$k}}">
                        {{$k+1}}
                      </button>
                    </h5>
                  </div>
                <div id="collapse{{$k}}" class="collapse" aria-labelledby="heading{{$k}}" data-parent="#accordion">
                    <div class="card-body">
                        {!! formKriteria($dataNumber) !!}  
                    </div>
                </div>
            </div>
        </div>
        @endforeach
</div>
@endsection
@section('page-js')
<script type="text/javascript">
    $(document).ready(function() {
      $('input[type="checkbox"], input[type="radio"], input[type="text"], textarea').attr('disabled', true);
    });

   $('.page').on('click',function(e){
        e.preventDefault();
        let number = $(this).data('number');
        let base_url = "{{url('/')}}";
        // Tambahkan kelas active dan hapus dari yang lain
        $('.page').removeClass('active');
        $(this).addClass('active');

        $.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 
            }, // 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
                });
            },
            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
            }
        });        
   });

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

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

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

        let formData = {};
        let allData = {};
        let isValid = true; // Flag validasi

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

        $('.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

            if (type === 'radio' || type === 'checkbox') {
                // 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 {
                // 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;
        }

        $.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').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