@extends('layouts.master')

@section('page-css')
<link rel="stylesheet" media="screen, print" href="{{asset('assets/css/datagrid/datatables/datatables.bundle.css')}}">
<style type="text/css">
    .listItem{
        list-style: none;
        margin: 0;
        padding: 0;
    }
    .listItem > li{
        display: inline-block;
        margin: 10px;
    }
    .listItem > li:hover{
        cursor: pointer;
    }
    .listItem > li .number{
        font-size: 14px;
        color: #fff;
        background: #0ba360 !important;
        padding: 10px;
        border-radius: 10%;
    }
    .level{
        float: right;
        color: #fff;
        text-align: center;
        width: 100px;
    }
    .nav-link{
        border-radius: 0px!important;
    }
    .pageNumber{ list-style:none; padding:0px; margin: 0px;}
    .pageNumber > li{ display: inline-block; padding: 12px; background: rgba(255, 255, 255, 0.5); margin: 5px 1px;}
    .pageNumber > li:hover{cursor: pointer;}
    .page.activePage {
        background-color: #007bff; /* Warna biru */
        color: white;
        font-weight: bold;
    }
</style>
@endsection
@section('content')
<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">{{$sekolah->nama_sekolah}}</h5>
                                <p class="mb-0">NPSN: {{$sekolah->npsn}}</p>
                            </div>
                            <div class="d-flex flex-column gap-1">
                                <span class="badge bg-primary-light text-primary">{{$sekolah->tingkat->name}}</span>
                                <span class="badge bg-success-light text-success">{{$sekolah->status}}</span>
                                <span class="badge bg-info-light text-info">Level {{levelAdiwiyata($sekolah->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
        <form method="POST" id="form">
        <input type="hidden" name="secure_id" value="{{encode_id($kuesioner->KuesionerId)}}">
        {{csrf_field()}}
            <div class="">
                <div class="">
                    <div class="row">
                        
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <ul class="nav nav-tabs" role="tablist">
                                        <li class="nav-item"><a class="nav-link" data-toggle="tab" href="#profile">Profile Sekolah</a></li>
                                        <!-- <li class="nav-item"><a class="nav-link" data-toggle="tab" href="#dokumen">Dokumen Administrasi</a></li> -->
                                        <li class="nav-item"><a class="nav-link active" data-toggle="tab" href="#kriteria">Pemenuhan Kriteria</a></li>
                                        <li class="nav-item"><a class="nav-link" data-toggle="tab" href="#usulan">Usulan CSA</a></li>
                                    </ul>
                                </div>
                            </div>
                            
                            <div class="tab-content py-3">
                                <div class="tab-pane fade" id="profile" role="tabpanel">
                                   <div class="card my-2">
                                        <div class="card-header bg-white">
                                            <h5 class="mb-0 fw-500">Data Jumlah</h5>
                                        </div>
                                        <div class="card-body">
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label>Jumlah Peserta Didik</label>
                                                        <input disabled name="jumlah_peserta_didik" value="{{@$jumlah_peserta_didik ? @$jumlah_peserta_didik : old('jumlah_peserta_didik')}}" type="text" class="numberInput form-control form-control-sm" placeholder="jumlah peserta didik">
                                                    </div>
                                                    <div class="form-group">
                                                        <label>Jumlah Tenaga kependidikan</label>
                                                        <input readonly name="jumlah_tenaga_kependidikan" value="{{@$jumlah_tenaga_kependidikan ? @$jumlah_tenaga_kependidikan : old('jumlah_tenaga_kependidikan')}}" type="text" class="numberInput form-control form-control-sm" placeholder="jumlah tenaga kependidikan">
                                                    </div>
                                                    <div class="form-group">
                                                        <label>Jumlah Biopori</label>
                                                        <input readonly name="jumlah_biopori" value="{{@$jumlah_biopori ? @$jumlah_biopori : old('jumlah_biopori')}}" type="text" class="numberInput form-control form-control-sm" placeholder="jumlah biopori">
                                                    </div>
                                                    <div class="form-group">
                                                        <label>Jumlah Pohon/Tanaman yang ditanam dan tumbuh</label>
                                                        <input readonly name="jumlah_pohon" value="{{@$jumlah_pohon ? @$jumlah_pohon : old('jumlah_pohon')}}" type="text" class="numberInput form-control form-control-sm" placeholder="jumlah pohon tanaman">
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label>Jumlah Tenaga Pendidik</label>
                                                        <input readonly name="jumlah_tenaga_pendidik" value="{{@$jumlah_tenaga_pendidik ? @$jumlah_tenaga_pendidik : old('jumlah_tenaga_pendidik')}}" type="text" class="numberInput form-control form-control-sm" placeholder="jumlah tenaga pendidik">
                                                    </div>
                                                    <div class="form-group">
                                                        <label>Jumlah Warga Sekolah Lainnya</label>
                                                        <input readonly name="jumlah_warga_sekolah_lainnya" value="{{@$jumlah_warga_sekolah_lainnya ? @$jumlah_warga_sekolah_lainnya : old('jumlah_warga_sekolah_lainnya')}}" type="text" class="numberInput form-control form-control-sm" placeholder="jumlah warga lainnya (cont:petugas kebersihan, petugas keamanan, petugas kantin, dll)">
                                                    </div>
                                                    <div class="form-group">
                                                        <label>Jumlah Sumur Resapan</label>
                                                        <input readonly name="jumlah_sumur_resapan" value="{{@$jumlah_sumur_resapan ? @$jumlah_sumur_resapan : old('jumlah_sumur_resapan')}}" type="text" class="numberInput form-control form-control-sm" placeholder="jumlah sumur resapan">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="card my-2">
                                        <div class="card-header bg-white">
                                            <h5 class="mb-0 fw-500">Penghematan air sebelum dan setelah melaksanakan gerakan PBLHS</h5>
                                        </div>
                                        <div class="card-body">
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label>Sebelum melaksanakan gerakan PBLHS <br> <small class="text-info">(Meter Kubik/Bulan)</small></label>
                                                        <input readonly name="air_sebelum_pblhs" value="{{@$air_sebelum_pblhs ? @$air_sebelum_pblhs : old('air_sebelum_pblhs')}}" type="text" class="numberInput form-control form-control-sm" placeholder="rata-rata per bulan dalam meter kubik">
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <label>Setelah melaksanakan gerakan PBLHS <br> <small class="text-info">(Meter Kubik/Bulan)</small></label>
                                                    <input readonly name="air_setelah_pblhs" value="{{@$air_setelah_pblhs ? @$air_setelah_pblhs : old('air_setelah_pblhs')}}" type="text" class="numberInput form-control form-control-sm" placeholder="rata-rata per bulan dalam meter kubik">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="card my-2">
                                        <div class="card-header bg-white">
                                            <h5 class="mb-0 fw-500">Penghematan listrik sebelum dan setelah melaksanakan gerakan PBLHS</h5>
                                        </div>
                                        <div class="card-body">
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label>Sebelum melaksanakan gerakan PBLHS <br> <small class="text-info">(KWH/Bulan)</small><br> <small class="text-info"></small></label>
                                                        <input readonly name="listrik_sebelum_pblhs" value="{{@$listrik_sebelum_pblhs ? @$listrik_sebelum_pblhs : old('listrik_sebelum_pblhs')}}" type="text" class="numberInput form-control form-control-sm" placeholder="rata-rata per bulan dalam kwh">
                                                    </div>
                                                    <div class="form-group">
                                                        <label>Luas ruangan ber AC</label>
                                                        <input readonly name="luas_ruangan_ac" value="{{@$luas_ruangan_ac ? @$luas_ruangan_ac : old('luas_ruangan_ac')}}" type="text" class="numberInput form-control form-control-sm" placeholder="dalam satuan meter persegi">
                                                    </div>
                                                    <div class="form-group">
                                                        <label>Jumlah Kader</label>
                                                        <input readonly name="jumlah_kader" value="{{@$jumlah_kader ? @$jumlah_kader : old('jumlah_kader')}}" type="text" class="numberInput form-control form-control-sm" placeholder="jml kader yang dibentuk dan diberdayakan selama pelaksanaan gerakan PBLHS">
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label>Setelah melaksanakan gerakan PBLHS <br> <small class="text-info">(KWH/Bulan)</small></label>
                                                        <input readonly name="listrik_setelah_pblhs" value="{{@$listrik_setelah_pblhs ? @$listrik_setelah_pblhs : old('listrik_setelah_pblhs')}}" type="text" class="numberInput form-control form-control-sm" placeholder="rata-rata per bulan dalam kwh">
                                                    </div>
                                                    <div class="form-group">
                                                        <label>Luas ruangan non AC</label>
                                                        <input readonly name="luas_ruangan_non_ac" value="{{@$luas_ruangan_non_ac ? @$luas_ruangan_non_ac : old('luas_ruangan_non_ac')}}" type="text" class="numberInput form-control form-control-sm" placeholder="dalam satuan meter persegi">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="tab-pane fade active show" id="kriteria" role="tabpanel">
                                    <div class="row">
                                        <div class="col-md-4">
                                            <div class="card">
                                                <div class="card-body">
                                                    <div class="my-3 text-center ">
                                                        <a href="#" class="btn btn-outline-primary mr-2 ">
                                                            Sekolah
                                                            <br>
                                                            <h4 class="nilai_sekolah">{{getNilai('sekolah',1,$sekolah->MsSekolahId,$kuesioner->KuesionerId)}}</h4>
                                                        </a>
                                                        <a href="#" class="btn btn-outline-warning mr-2 ">
                                                            Kab/Kota
                                                            <br>
                                                            <h4 class="nilai_kota">{{getNilai('kota',1,$sekolah->MsSekolahId,$kuesioner->KuesionerId)}}</h4>
                                                        </a>
                                                    </div>
                                                    <div class="pageNumber row gap-1 justify-content-center">
                                                        @foreach($page as $hal)
                                                        <div class="col-3 text-center page {{ (checkPenilaian($hal,$sekolah->MsSekolahId,'kota',$kuesioner->KuesionerId) == true ? 'bg-success-light text-success border-success rounded' : 'border-secondary rounded' )}}" data-number={{$hal}}>
                                                                <span>{{$hal}}</span>
                                                        </div>
                                                        @endforeach
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-8">
                                            <div class="card">
                                                <div class="card-body">
                                                    <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. Perencanaan Gerakan PBLHS</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,$sekolah->MsSekolahId,'kota',tahunKuesioner($kuesioner->KuesionerId)) !!}
                                                            </div>
                                                        </div>
                                                        @if(session('group_id') == 6)
                                                            @if(@$kuesioner->status < 4)
                                                                <div class="col-md-12 mt-3">
                                                                    <button id="btnSave" class="btn btn-success"><i class="fal fa-save"></i>&nbsp;Simpan Data</button>
                                                                </div>
                                                            @endif
                                                        @endif
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="tab-pane fade" id="usulan" role="tabpanel">
                                    <div class="card">
                                        <div class="card-header bg-white">
                                            <h4 class="mb-0 fw-500">Form Validasi</h4>
                                        </div>
                                        <div class="card-body">
                                            <div class="row">
                                                <div class="col-12">
                                                    <div class="alert bg-primary-light text-primary mb-3">
                                                        <i class="fal fa-info-circle"></i>&nbsp;Pastikan sebelum melakukan simpan data validasi, pemenuhan kriteria sudah lengkap diisi!
                                                    </div>
                                                </div>
                                                <div class="col-md-6 my-2">
                                                    <div class="form-group">
                                                        <label class="fw-500">Jenis Usulan CSA</label>
                                                        <input disabled type="text" class="form-control" name="" value="{{getUsulan($sekolah->MsSekolahId)}}">
                                                    </div>
                                                </div>
                                                <div class="col-md-6 my-2">
                                                    <div class="form-group">
                                                        <label class="fw-500">Validasi</label>
                                                        <select class="form-control select2" id="validasi" name="validasi">
                                                            <option value="">- Pilih Validasi -</option>
                                                            <option {{@$kuesioner->status == '4' || @$kuesioner->status == '10' ? 'selected' : ''}} value="1">Selesai</option>
                                                            <option {{@$kuesioner->status == '5' ? 'selected' : ''}} value="2">Dikembalikan</option>
                                                        </select>
                                                    </div>
                                                </div>
                                                <div class="col-md-12 my-2">
                                                    <div class="form-group">
                                                        <label class="fw-500">Catatan</label>
                                                        <textarea class="form-control" id="catatan_validasi" name="catatan_validasi" placeholder="Catatan">{{@$kuesioner->catatan_usulan}}</textarea>
                                                    </div>
                                                </div>
                                                @if(session('group_id') == 6)
                                                    @if(@$kuesioner->status < 4)
                                                        <div class="col-md-12 my-2">
                                                            <button id="btnSaveUsulan" class="btn btn-success"><i class="fal fa-save"></i>&nbsp;Simpan Data</button>
                                                        </div>
                                                    @endif
                                                @endif
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        
                        
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5><b class="titleModal"></b></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true"><i class="fal fa-times"></i></span>
                </button>
            </div>
            <div class="modal-body">
                <div class="bodyModal text-center"></div>
            </div>
        </div>
    </div>
</div>
@endsection
@section('page-js')
<script type="text/javascript">
    $(document).on('change', '.uncheckall', function () {
        if ($(this).is(':checked')) {
            $('.checklistInput').not(this).prop('checked', false);
        }
    });

    $(document).on('change', '.checklistInput:not(.uncheckall)', function () {
        if ($(this).is(':checked')) {
            $('.uncheckall').prop('checked', false);
        }
    });

    $('.clickModal').on('click',function(){
        $('.remove').remove();
        const fileType = $(this).data('type');
        const title = $(this).data('title');
        const url = $(this).data('url');

        $('.titleModal').html(title);
        
        if (fileType === 'pdf') {
            var body = `<iframe class="remove" src="${url}" width="100%" height=500"></iframe>`;
        } else {
            var body = `<img class="remove" src="${url}" width="70%" style="max-width:100%; max-height:50%;">`;
        }

        $('.bodyModal').append(body);

    });
    @if(@$kuesioner->status < 4)
    $(document).ready(function() {
      // $('input[type="checkbox"], input[type="radio"], input[type="text"], textarea').attr('disabled', true);
    });
    @endif
   $('.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('bg-primary-light border-primary text-primary');
        $(this).addClass('bg-primary-light border-primary text-primary');

        $.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,
                type:'kota',
                kuesionerId: '{{ $kuesioner->KuesionerId }}' ,
                sekolah: "{{encode_id(@$sekolah->MsSekolahId)}}"
            }, // 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);
                $('.nilai_sekolah').html(response.nilai_sekolah);
                $('.nilai_kota').html(response.nilai_kota);
                $('.nilai_provinsi').html(response.nilai_prov);

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

                $('.clickModal').on('click',function(){
                    $('.remove').remove();
                    const fileType = $(this).data('type');
                    const title = $(this).data('title');
                    const url = $(this).data('url');

                    $('.titleModal').html(title);
                    
                    if (fileType === 'pdf') {
                        var body = `<iframe class="remove" src="${url}" width="100%" height=500"></iframe>`;
                    } else {
                        var body = `<img class="remove" src="${url}" width="70%" style="max-width:100%; max-height:50%;">`;
                    }

                    $('.bodyModal').append(body);

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

   $('.resume').on('click',function(e){
        window.location.href = "{{url('usulan/csak/resume/'.encode_id($sekolah->MsSekolahId))}}";
   });
    $('#btnSaveUsulan').on('click',function(e){
        e.preventDefault();

        var validasi = $('#validasi').find(':selected').val();
        var catatan_validasi = $('#catatan_validasi').val();
        if(validasi == ''){
            toastr.error("Validasi Belum Dipilih", 'Error!', {positionClass: 'toast-bottom-right', containerId: 'toast-bottom-right'});
            return;
        }
        if(catatan_validasi == ''){
            toastr.error("Catatan Validasi Belum Diisi", 'Error!', {positionClass: 'toast-bottom-right', containerId: 'toast-bottom-right'});
            return;
        }

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

                    location.reload();
                }else{
                    toastr.error(response.message, 'Error!', {positionClass: 'toast-bottom-right', containerId: 'toast-bottom-right'});
                }

            },
            error: function (xhr, status, error) {
                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
            }
        });

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

        const nama_dalam_sk = $('input[name="dokumen_1"]:checked').val();
        const sk_ttd = $('input[name="dokumen_2"]:checked').val();
        const waktu_penetapan = $('input[name="dokumen_3"]:checked').val();

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

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

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

        $.ajax({
            url: "{{route('modules.usulan_adiwiyata.administrasi.update')}}", // Ganti dengan URL API-mu
            type: 'POST', // Bisa juga 'POST' kalau perlu
            xhrFields: {
                withCredentials: true
            },
            data: { 
                _token:'{{csrf_token()}}',
                nama_dalam_sk: nama_dalam_sk,
                sk_ttd: sk_ttd,
                waktu_penetapan: waktu_penetapan,
                sekolah: "{{encode_id(@$sekolah->MsSekolahId)}}"
            }, // Kirim number sebagai parameter
            dataType: 'json', // Format respons JSON
            beforeSend: function () {
                $('#loading-spinner').show(); // Menampilkan spinner
            },
            success: function (response) {
                if(response.status == true){
                    toastr.success("Berhasil menyimpan data", 'Success!', {positionClass: 'toast-bottom-right', containerId: 'toast-bottom-right'});
                }else{
                    toastr.error("Maaf Terjadi Kesalahan Menyimpan Data", 'Error!', {positionClass: 'toast-bottom-right', containerId: 'toast-bottom-right'});
                }
            },
            error: function (xhr, status, error) {
                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
            }
        });


    });
    $('#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);
            
        }

        formData.append('sekolah', "{{encode_id(@$sekolah->MsSekolahId)}}");

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

        // =========================
        // AJAX SUBMIT
        // =========================
        $.ajax({
            url: "{{route('modules.usulan_adiwiyata.kriteria.store')}}", // Ganti dengan URL API-mu
            type: "POST",
            data: formData,
            xhrFields: {
                withCredentials: true
            },
            processData: false, // WAJIB
            contentType: false, // WAJIB
            beforeSend: function () {
                $('#loading-spinner').show();
            },
            success: function (response) {
                toastr.success("Berhasil menyimpan data", 'Success!', {positionClass: 'toast-bottom-right', containerId: 'toast-bottom-right'});
                $('.nilai_kota').html(response.nilai_kota);
                $('.nilai_provinsi').html(response.nilai_prov);
                $('.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');
            },
            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

        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') {
                // 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;
        }

        $.ajax({
            url: "{{route('modules.usulan_adiwiyata.kriteria.store')}}", // Ganti dengan URL API-mu
            type: 'POST', // Bisa juga 'POST' kalau perlu
            xhrFields: {
                withCredentials: true
            },
            data: { 
                _token:'{{csrf_token()}}',
                data: allData,
                sekolah: "{{encode_id(@$sekolah->MsSekolahId)}}"
            }, // 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'});
                $('.nilai_kota').html(response.nilai_kota);
                $('.nilai_provinsi').html(response.nilai_prov);
                $('.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');
            },
            error: function (xhr, status, error) {
                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