@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;}
    .pageNumber > li.active {
        background-color: #007bff; /* Warna biru */
        color: white;
        font-weight: bold;
    }
</style>
@endsection
@section('content')
<div class="subheader">
    <h1 class="subheader-title">
        <i class='subheader-icon fal fa-edit'></i> {{$title}}
    </h1>
</div>
<div class="row">
    <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">
        {{csrf_field()}}
            <div class="card">
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-12 p-3">
                            <table class="" border="0" style="width:100%">
                                <tr>
                                    <td rowspan="5" width="5" style="vertical-align: middle; padding-right: 10px;">
                                        <i class="fal fa-building fa-5x"></i>
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan="2"><h5 class="text-success">NPSN: {{$sekolah->npsn}}</h5></td>
                                </tr>
                                <tr>
                                    <td colspan="2"><h4><b>{{$sekolah->nama_sekolah}}</b></h4></td>
                                </tr>
                                <tr>
                                    <td colspan="2"><span class="badge badge-primary">{{$sekolah->tingkat->name}}</span> <span class="badge badge-success">{{$sekolah->status}}</span></td>
                                </tr>
                            </table>
                        </div>
                        <div class="col-md-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>
                        <div class="col-md-12 mb-4" style="background: rgba(23, 162, 184, 0.2) !important;">
                            <ul class="pageNumber">
                                <li class="back"><i class="fal fa-arrow-left"></i></li>
                                <li class="resume active">Resume</li>
                            </ul>
                        </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">
                                @foreach($page as $dataNumber)
                                <div class="card mb-2" style="background:#EDE8DC;">
                                    <div class="card-header color-white bg-success">
                                        {{$dataNumber}}
                                    </div>
                                    <div class="card-body color-black">
                                        {!! formKriteria($dataNumber,$sekolah->MsSekolahId) !!}  
                                    </div>
                                </div>
                                @endforeach
                            </div>
                        </div>
                        
                    </div>
                </div>
                
            </div>
        </form>
    </div>
</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
            data: { 
                _token:'{{csrf_token()}}',
                page: number ,
                sekolah: {{@$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);

                $('.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/csam/update/'.encode_id($sekolah->MsSekolahId))}}";
   });

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