@extends('layout.template')

@section('intitule')
    <h4 class="text-uppercase mb-0">INSERTION DES NOTES: {{ $data['intituleUE'] }}</h4>
@endsection

@section('breadcrumb')
    <li class="breadcrumb-item active" aria-current="page">Insertion notes</li>
@endsection

@section('styles')
    <link href="{{ asset('assets/libs/jquery-steps/jquery.steps.css') }}" rel="stylesheet">
    <link href="{{ asset('assets/extra-libs/datatables.net-bs4/css/dataTables.bootstrap4.css') }}" rel="stylesheet">

    <link href="{{ asset('assets/extra-libs/toastr/dist/build/toastr.min.css') }}" rel="stylesheet">
    <link rel="stylesheet" type="text/css"
        href="{{ asset('assets/extra-libs/datatables.net-bs4/css/responsive.dataTables.min.css') }}">
    <link href="{{ asset('assets/libs/jquery-steps/steps.css') }}" rel="stylesheet">
    <link href="{{ asset('assets/my_css/style.css') }}">
@endsection
@section('main')
    <div class="row justify-content-center mt-4" style="min-height: calc(85vh - 60px)">
        <div class="col-lg-12">
            <div class="bg-white" style="padding: 25px">
                <h3 class="box-title m-b-0">Notes des étudiants</h3>
                <p class="text-muted m-b-30 font-13"> Ce formulaire permet de renseigner la note des étudiants par EC.</p>
                <div class="col-12">
                    <div class="card">
                        <div class="card-body wizard-content p-0">
                            <h6 class="card-subtitle mb-3"></h6>
                            <form action="{{ route('insertion.normale.note1') }}" class="tab-wizard wizard-circle">
                                <!-- Step 1 -->
                                <h6> {{ $data['intituleECU'] }}</h6>
                                <section>
                                    <div class="row justify-content-center py-3"
                                        style="padding-left: 15%!important;padding-right:15%!important;">

                                        <table id="datatable" cellpadding="10px" style="border: 1px solid #e9ecef"
                                            class="table table-striped table-hover table-bordered " role="grid">
                                            <thead class="text-info">
                                                <td>#</td>
                                                <td>Matricule</td>
                                                <td>Noms &amp; Prénoms</td>
                                                <td style="width:150px">
                                                    Notes</td>
                                            </thead>
                                            <?php
                                            $counter = 1;
                                            ?>
                                            <tbody>
                                                @if ($data['operation'] == 0)
                                                    {{-- Insertion par ec --}}
                                                    @foreach ($data['students'] as $student)
                                                        <tr>
                                                            <td style="width:75px!important">
                                                                {{ $counter }}</td>
                                                            <td style="width:150px!important">{{ $student->matricule }}
                                                            </td>
                                                            <td>{{ $student->nomPrenom }}</td>
                                                            <td><input type="number" min="0"
                                                                    max="{{ $data['echelle'] }}" step="0.1"
                                                                    name="{{ $student->matricule }}"
                                                                    id="note{{ $counter }}"
                                                                    style="width:200px;border: 1px solid #e9ecef;" required>
                                                                <span style="display:none">Entrer une valeur valide</span>
                                                            </td>
                                                        </tr>
                                                        <?php
                                                        $counter++;
                                                        ?>
                                                    @endforeach
                                                @elseif ($data['operation'] == 1)
                                                    {{-- Insertion par controle/Examen --}}
                                                    @foreach ($data['students'] as $student)
                                                        <tr>
                                                            <td style="width:75px!important">
                                                                {{ $counter }}</td>
                                                            <td style="width:150px!important">{{ $student->matricule }}
                                                            </td>
                                                            <td>{{ $student->nomPrenom }}</td>
                                                            <td><input type="number" min="0"
                                                                    max="{{ $data['echelle'] }}" step="0.1"
                                                                    name="{{ $student->matricule }}"
                                                                    id="noteE{{ $counter }}"
                                                                    style="width:200px;border: 1px solid #e9ecef;" required
                                                                    placeholder="Examen">
                                                                <span style="display:none">Entrer une valeur valide</span>
                                                                <input type="number" min="0"
                                                                    max="{{ $data['echelle'] }}" step="0.1"
                                                                    name="{{ $student->matricule }}"
                                                                    id="noteC{{ $counter }}"
                                                                    style="width:200px;border: 1px solid #e9ecef;" required
                                                                    placeholder="Controle Continu">
                                                                <span style="display:none">Entrer une valeur valide</span>
                                                            </td>
                                                        </tr>
                                                        <?php
                                                        $counter++;
                                                        ?>
                                                    @endforeach
                                                @elseif ($data['operation'] == 4)
                                                    {{-- Insertion parUE --}}
                                                    @foreach ($data['students'] as $student)
                                                        <tr>
                                                            <td style="width:75px!important">
                                                                {{ $counter }}</td>
                                                            <td style="width:150px!important">{{ $student->matricule }}
                                                            </td>
                                                            <td>{{ $student->nomPrenom }}</td>
                                                            <td><input type="number" min="0"
                                                                    max="{{ $data['echelle'] }}" step="0.1"
                                                                    name="{{ $student->matricule }}"
                                                                    id="note{{ $counter }}"
                                                                    style="width:200px;border: 1px solid #e9ecef;" required>
                                                                <span style="display:none">Entrer une valeur valide</span>
                                                            </td>
                                                        </tr>
                                                        <?php
                                                        $counter++;
                                                        ?>
                                                    @endforeach
                                                @endif
                                            </tbody>
                                        </table>
                                    </div>
                                </section>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>



    
@endsection
@section('scripts')
    <script src="{{ asset('assets/libs/jquery-steps/build/jquery.steps.min.js') }}"></script>
    <script src="{{ asset('assets/extra-libs/datatables.net/js/jquery.dataTables.min.js') }}"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.4.29/dist/sweetalert2.all.min.js"></script>
    <script src="{{ asset('assets/extra-libs/toastr/dist/build/toastr.min.js') }}"></script>
    <script src="{{ asset('assets/extra-libs/datatables.net-bs4/js/dataTables.responsive.min.js') }}"></script>

    <script src="{{ asset('dist/js/pages/datatable/datatable-basic.init.js') }}"></script>
    <script>
        $(() => {
            let isValid = (id) => {
                $(id).css({
                    "border-color": "#2cd07e",
                    "background-image": "url(\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%232cd07e' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z' /%3e%3c/svg%3e\")",
                    "padding-right": "calc(1.5em + 0.75rem)",
                    "background-repeat": "no-repeat",
                    "background-position": "right calc(0.375em + 0.1875rem) center",
                    "background-size": "calc(0.75em + 0.375rem) calc(0.75em + 0.375rem)"
                });
                $(id).next().css({
                    "display": "none",
                });
            }
            let isInvalid = (id) => {
                $(id).css({
                    "border-color": "#ff5050",
                    "background-image": "url(\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23ff5050' %3e%3ccircle cx='6' cy='6' r='4.5' /%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z' /%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23ff5050' stroke='none' /%3e%3c/svg%3e\")",
                    "padding-right": "calc(1.5em + 0.75rem)",
                    "background-repeat": "no-repeat",
                    "background-position": "right calc(0.375em + 0.1875rem) center",
                    "background-size": "calc(0.75em + 0.375rem) calc(0.75em + 0.375rem)"
                });
                $(id).next().css({
                    "display": "block",
                    "width": "100%",
                    "margin-top": "0.25rem",
                    "font-size": "0.875em",
                    "color": "#ff5050"
                })
            }
            let allCaseValid = () => {
                all = [];
                @if ($data['mode'] != 'S')
                    for (let i = 1; i < {{ $counter }}; i++) {
                        all.push(checkNullValidation("#note" + i));
                    }
                @else
                    for (let i = 1; i < {{ $counter }}; i++) {
                        all.push(checkNullValidation("#noteE" + i));
                        all.push(checkNullValidation("#noteC" + i));
                    }
                @endif

                return all.every(value => value === true);
            }
            //Vérifie si les élements des formulaires sont vide
            let checkNullValidation = (id) => {
                if ($(id).val() === '' || $(id).val() === undefined || ($(id).val() < 0 || $(id).val() >
                        {{ $data['echelle'] }})) {
                    isInvalid(id);
                    return false;
                } else {
                    isValid(id);
                    return true;
                }
            }
            $(document).ready(function() {
                $('#datatable').DataTable({
                    "lengthChange": false,
                    "scrollcollapse": true,
                    "paging": false,
                    "scrollY": "450px"
                });
            });
            //Custom design form example

            

            $(".tab-wizard").steps({
                headerTag: "h6",
                bodyTag: "section",
                transitionEffect: "fade",
                titleTemplate: '<span class="step">#index#</span> #title#',
                labels: {
                    finish: "Submit"
                },
                onFinished: function(event, currentIndex) {
                    if (allCaseValid()) {

                        Swal.fire({
                            title: 'Confirmer cette opération?',
                            text: "Cette opération ajoutera les notes des étudiants dans la base",
                            icon: 'info',
                            showCancelButton: true,
                            confirmButtonColor: 'rgb(44, 208, 126)',
                            cancelButtonColor: '#d33',
                            cancelButtonText: 'Annuler',
                            reverseButtons: true,
                            confirmButtonText: 'Confirmer l\'opération',
                            backdrop: true,

                            preConfirm: () => {
                                let url = "{{ route('insertion.normale.note1') }}";

                                @if ($data['mode'] != 'S')
                                    all = {};
                                    for (let i = 1; i < {{ $counter }}; i++) {
                                        all[$("#note" + i).attr('name')] = $("#note" + i)
                                            .val();
                                    }
                                @else
                                    all = {
                                        noteC: {},
                                        noteE: {}
                                    };
                                    for (let i = 1; i < {{ $counter }}; i++) {
                                        all['noteE'][$("#noteE" + i).attr('name')] = $(
                                            "#noteE" + i).val();
                                        all['noteC'][$("#noteC" + i).attr('name')] = $(
                                            "#noteC" + i).val();
                                    }
                                @endif
                                let token = document
                                    .querySelector('meta[name="csrf-token"]')
                                    .getAttribute("content");

                                let options = {
                                    headers: 
                                    {
                                        "Content-Type": "application/json",
                                        Accept: "application/json, text-plain, */*",
                                        "X-Requested-With": "XMLHttpRequest",
                                        "X-CSRF-TOKEN": token,
                                    },
                                    method: "post",
                                    credentials: "same-origin",
                                    body: JSON.stringify(
                                        {
                                            acadYear: "{{ $data['acadYear'] }}",
                                            idFiliere: "{{ $data['idFiliere'] }}",
                                            formation: "{{ $data['formation'] }}",
                                            etudeYear: "{{ $data['etudeYear'] }}",
                                            notes: all,
                                            operation: "{{ $data['operation'] }}",
                                            intituleEcu: "{{ $data['intituleECU'] }}",
                                            code_unite: "{{ $data['code_unite'] }}",
                                            code_ecu: "{{ $data['code_ecu'] }}",
                                            ip: "{{ $data['ip'] }}",
                                            echelle: "{{ $data['echelle'] }}"
                                        }),
                                };



                            //     return fetch(url, options)
                            //     .then((response) => response.json())
                            //     .then((response) => {
                            //     if (response.success) {
                            //         // L'opération a réussi
                            //         Swal.fire(
                            //             'Opération réussie',
                            //             'Les données ont été insérées avec succès.',
                            //             'success'
                            //         );
                            //     } else {
                            //         // L'opération a échoué
                            //         Swal.fire({
                            //             icon: 'error',
                            //             title: 'Oops...',
                            //             text: 'L\'opération a échoué. Veuillez réessayer.',
                            //         });
                            //     }
                            // })
                            // .catch((e) => {
                            //     // Une erreur s'est produite lors de la requête AJAX
                            //     console.error("Une erreur s'est produite lors de la requête AJAX : " + e.message);
                            // });


                                return fetch(url, options)
                                    .then((response) => response.json())
                                    .then((response) => {
                                        console.log(response);
                                if (!response.success) {
                                    throw new Error("L'opération à échoué");
                                };
                                    })
                                    .catch((e) => {
                                        throw new Error("L'opération à échoué");
                                    });
                            },
                            allowOutsideClick: () => !Swal.isLoading(),
                            showLoaderOnConfirm: true
                        }).then((result) => {
                            if (result.isConfirmed) {
                                Swal.fire(
                                    'Insertion des notes de {{ $counter - 1 }} étudiants',
                                    'réalisée avec succès.',
                                    'success'
                                );
                                window.location.replace("{{ route('insertion.normale') }}");
                            }
                        }).catch(() => {
                            Swal.fire({
                                icon: 'error',
                                title: 'Oops...',
                                text: 'Une erreur s\'est produite lors de l\'insertion',

                            });
                        });
                    } else {
                        $('.wizard-content .wizard>.steps>ul>li').removeClass("done");
                        toaster("error", "Veuillez entrer toutes les notes...");
                    }
                }
            });
            for (let i = 1; i < {{ $counter }}; i++) {
                $("#note" + i).blur(() => {
                    checkNullValidation("#note" + i)
                });
                $("#noteE" + i).blur(() => {
                    checkNullValidation("#noteE" + i)
                });
                $("#noteC" + i).blur(() => {
                    checkNullValidation("#noteC" + i)
                });
            }
        });
    </script>
@endsection


