@extends('layouts.master')

@section('page-css')
@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">{{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>
    @if(($kuesioner->status == 1) || ($kuesioner->status == 5))
    <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>
    @endif
    <div class="col-md-12 mb-2">
        <a href="{{ url('usulan/adiwiyata/kriteria') }}" class="btn btn-primary"><i class="fal fa-arrow-left"></i>&nbsp; Kembali</a>
    </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

    <div class="col-md-6 d-none">
        <div class="card">
            <div class="card-body">
                <h4 class="mb-3 fw-700">Status Usulan</h4>
                <?php
                    if(($kuesioner->level+1) == 1){
                        $jenis_usulan = 'Kabupaten/Kota';
                    }elseif(($kuesioner->level+1) == 2){
                        $jenis_usulan = 'Provinsi';
                    }elseif(($kuesioner->level+1) == 3){
                        $jenis_usulan = 'Nasional';
                    }elseif(($kuesioner->level+1) == 4){
                        $jenis_usulan = 'Mandiri';
                    }
                ?>
                <p>
                    Sekolah diusulan untuk menjadi CSA (Calon Sekolah Adiwiyata) <b>{{$jenis_usulan}}</b><br>
                </p>
                <span class="text-primary">Silahkan lengkapi data pada menu Usulan Adiwiyata. </span>
            </div>
        </div>
    </div>

    <div class="col-md-12">
        <form method="POST" id="form">
            {{csrf_field()}}
            <div class="card">
                <div class="card-body p-4">
                <h4 class="mb-3 fw-700">Kirim Kelengkapan Data</h4>
                {{-- <p>Kab/Kota akan melakukan validasi, jika data sekolah lengkap akan diproses. apabila data belum lengkap akan dikembalikan ke sekolah untuk melakukan perbaikan. </p> --}}
                <div class="alert bg-primary-light mb-3">
                    <p class="text-primary mb-0">Pastikan data Pemenuhan Kriteria telah sesuai sebelum melanjutkan proses selanjutnya.</p>
                </div>
                <div class="d-flex flex-column gap-3">
                    <div class="d-flex flex-row justify-content-between">
                        <div>
                            <i class="fal fa-trophy"></i>&nbsp;Usulan Adiwiyata
                        </div>
                        <div>
                            <?php
                                if(($kuesioner->level+1) == 1){
                                    $jenis_usulan = 'Kabupaten/Kota';
                                }elseif(($kuesioner->level+1) == 2){
                                    $jenis_usulan = 'Provinsi';
                                }elseif(($kuesioner->level+1) == 3){
                                    $jenis_usulan = 'Nasional';
                                }elseif(($kuesioner->level+1) == 4){
                                    $jenis_usulan = 'Mandiri';
                                }
                            ?>
                            <span class="fw-500">Calon Sekolah Adiwiyata {{$jenis_usulan}}</span>
                        </div>
                    </div>
                    <div class="d-flex flex-row justify-content-between">
                        <div>
                            <i class="fal fa-envelope"></i>&nbsp;Dokumen Administrasi 
                        </div>
                        <div>
                            @if(@$dok)
                                @if(@$dok->status == 1)
                                    <span class="badge bg-success text-white">Dokumen Sudah Di Verifikasi</span>
                                @elseif(@$dok->status == 2)
                                    <span class="badge bg-danger text-white">Dokumen Ditolak</span>
                                @else
                                    <span class="badge bg-warning text-white">Menunggu Verifikasi Dokumen</span>
                                @endif
                            @else
                                <span class="badge bg-danger text-white">Belum Upload Dokumen</span>
                            @endif
                        </div>
                    </div>
                    <div class="d-flex flex-row justify-content-between">
                        <div>
                            <i class="fal fa-list"></i>&nbsp;Pemenuhan Kriteria
                        </div>
                        <div>
                            {{count(@$penilaian)}} / {{count(@$page)}} &nbsp;
                            @if(count(@$penilaian) == count(@$page))
                                <span class="badge bg-success text-white">Sudah Lengkap</span>
                            @else
                                <span class="badge bg-danger text-white">Belum Lengkap</span>
                            @endif
                        </div>
                    </div>
                    <div class="d-flex flex-row justify-content-between">
                        <div>
                            <i class="fal fa-pencil"></i>&nbsp;Nilai Pemenuhan Kriteria
                        </div>
                        <div>
                            {{ getNilaiAll('sekolah',$kuesioner->ms_sekolah_id,$kuesioner->KuesionerId) }}
                            @if(getNilaiAll('sekolah',$kuesioner->ms_sekolah_id,$kuesioner->KuesionerId) >= 80)
                                <span class="badge bg-success text-white">Nilai Lolos Verifikasi</span>
                            @else
                                <span class="badge bg-danger text-white">Nilai Belum Cukup</span>
                            @endif
                        </div>
                    </div>

                    
                </div>
                @if(session('group_alias') == 'sekolah')

                    @if(getNilaiAll('sekolah',$kuesioner->ms_sekolah_id,$kuesioner->KuesionerId) >= 80)
                    @else
                        <div class="alert alert-danger mt-5 pb-0">
                            <p>Nilai Pemenuhan Kriteria dinyatakan belum memenuhi ketentuan verifikasi dan perlu dilakukan perbaikan.</p>
                        </div>
                    @endif
                    <div class="d-flex flex-row justify-content-between my-3">
                        @if(session('group_alias') == 'sekolah')
                            @if(count(@$penilaian) == count(@$page))
                                @if(($kuesioner->status == 1) || ($kuesioner->status == 5))
                                    @if(getNilaiAll('sekolah',$kuesioner->ms_sekolah_id,$kuesioner->KuesionerId) >= 80)
                                        <div class="custom-control custom-checkbox">
                                            <input type="checkbox" class="custom-control-input is-required check" id="true" value="1" name="check">
                                            <label class="custom-control-label" for="true">Dengan ini menyatakan bahwa kelengkapan data sudah benar.</label>
                                        </div>
                                    @endif
                                @endif
                            @endif
                        @endif
                    </div>
                    @if(session('group_alias') == 'sekolah')
                        @if(@$kuesioner->status == 5)
                            <div class="alert alert-danger my-2">
                                Status : {!!kuesionerLogStatus(@$kuesioner->KuesionerId)!!} <br>
                                <p class="mb-0"><i>Pastikan isian sudah diperbaiki sebelum dikirim kembali</i></p>
                            </div>
                        @endif
                        @if(count(@$penilaian) == count(@$page))
                            @if(($kuesioner->status == 1) || ($kuesioner->status == 5))
                                @if(getNilaiAll('sekolah',$kuesioner->ms_sekolah_id,$kuesioner->KuesionerId) >= 80)
                                    <button class="btn btn-success btnSend">Kirim Data</button>
                                @endif
                            @endif
                        @endif
                    @endif
                @endif
              </div>
            </div>
            <div id="loading-spinner" style="display: none; text-align: center;">
                <img src="{{ asset('assets/spinner.gif') }}" alt="Loading..." width="20">
            </div>
        </form>
    </div>

    
</div>
@endsection
@section('page-js')
<script type="text/javascript">

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

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

        var check = $('.check');
        if (!check.is(':checked')) {
            toastr.error("Harap isi semua field yang wajib diisi", 'Error!', {positionClass: 'toast-bottom-right', containerId: 'toast-bottom-right'});
            // alert(".");
            return;
        }

        swal({
            title: "Kirim Data!",
            text: "Apa anda yakin ingin mengirim data pemenuhan kriteria ini ?",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#3F7D58",
            confirmButtonText: "Ya Kirim Sekarang",
            cancelButtonText: "Tidak",
            closeOnConfirm: true,
            closeOnCancel: true
        },
        function(isConfirm) {
            if(isConfirm){
                $.ajax({
                    url: "{{url('usulan/adiwiyata/kriteria/kirimData/'.@$secure_id.'/'.encode_id(@$kuesioner->KuesionerId))}}", // Ganti dengan URL API-mu
                    type: 'POST', // Bisa juga 'POST' kalau perlu
                    xhrFields: {
                        withCredentials: true
                    },
                    data: { 
                        _token:'{{csrf_token()}}',
                    }, // Kirim number sebagai parameter
                    dataType: 'json', // Format respons JSON
                    beforeSend: function () {
                        $('#loading-spinner').show(); // Menampilkan spinner
                    },
                    success: function (response) {
                        if(response.type == 'error'){
                            toastr.error(response.message, 'Error!', {positionClass: 'toast-bottom-right', containerId: 'toast-bottom-right'});
                        }else{
                            // console.log('Response:', response);
                            toastr.success("Berhasil menyimpan data", 'Success!', {positionClass: 'toast-bottom-right', containerId: 'toast-bottom-right'});
                            location.reload();
                        }
                        
                    },
                    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
                    }
                });
            }
        }); 
        return false;
        
    });

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