@extends('layout.template')

@section('intitule')
    <h4 class="text-uppercase mb-0">INSERTION DES NOTES PAR ELEMENT CONSTITUTIF </h4>
@endsection

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

@section('styles')
    <link rel="stylesheet" type="text/css" href="{{ asset('assets/libs/dropzone/dist/min/dropzone.min.css') }}">
    <link rel="stylesheet" href="{{ asset('dist/css/dropify.min.css') }}">
    <link href="{{ asset('assets/extra-libs/toastr/dist/build/toastr.min.css') }}" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="{{ asset('assets/libs/select2/dist/css/select2.min.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="card">
                <div class="card-header p-4"
                    style="background-color: {{ Session::get('RESULTAT_DATA')['RESULTAT_COULEUR_ETAB1'] }}; color: {{ Session::get('RESULTAT_DATA')['RESULTAT_COULEUR_TEXT1'] }};">
                    <h4 class="mb-0 text-white">Veuillez sélectionner les données s'il vous plait.</h4>
                </div>
                <div class="card-body">
                    <form class="form-horizontal" method="POST" action="{{ route('insertion.normale.list') }}"
                        id="submit" enctype="multipart/form-data">
                        @csrf
                        <div class="mb-3 pb-3 row border-bottom align-items-center">
                            <label for="" class="control-label text-md-end col-md-3">Opération</label>
                            <div class="col-md-6">
                                <select id="operation" name="operation" class="form-select p-2" required="">
                                    <option>Sélectionner le format</option>
                                    <optgroup label="TRAITEMENT SUR LE FORMULAIRE DE NOTES">
                                        <option value="4" {{ $data['mode'] != 'U' ? 'disabled' : '' }}>Insertion
                                            normale
                                            / Continuer une insertion :
                                            Format UE
                                        </option>
                                        <option value="0" {{ $data['mode'] != 'A' ? 'disabled' : '' }}>Insertion
                                            normale / Continuer une insertion : Format EC
                                        </option>
                                        <option value="1" {{ $data['mode'] != 'S' ? 'disabled' : '' }}>Insertion
                                            normale / Continuer une insertion :
                                            Format contrôle continue / Examen</option>
                                    </optgroup>
                                    <optgroup label="TRAITEMENT PAR FICHIER EXCEL">
                                        <option value="5" {{ $data['mode'] != 'U' ? 'disabled' : '' }}>Insertion par
                                            fichier excel : Format UE
                                        </option>
                                        <option value="2" {{ $data['mode'] != 'S' ? 'disabled' : '' }}>Insertion par
                                            fichier excel : Format contrôle continue /
                                            examen
                                        </option>
                                        <option value="3" {{ $data['mode'] != 'A' ? 'disabled' : '' }}>Insertion par
                                            fichier excel : Format EC</option>
                                    </optgroup>
                                </select>
                                <div class="invalid-feedback">
                                    L'opération est requise
                                </div>
                            </div>
                        </div>
                        <div class="mb-3 pb-3 row border-bottom align-items-center">
                            <label for="" class="control-label text-md-end col-md-3">Filière</label>
                            <div class="col-md-6">
                                <select class="select2 p-2" style="width: 100%" id="filiere" name="idFiliere">
                                    <option>Selectionner la filière</option>
                                    @foreach ($data['filieres'] as $filiere)
                                        <option value="{{ $filiere->idFiliere }}">
                                            {{ $filiere->intituleFilieres }}({{ $filiere->sigleFilieres }})</option>
                                    @endforeach
                                </select>
                                <div class="invalid-feedback">
                                    La filière est requise
                                </div>
                            </div>
                        </div>
                        <div class="mb-3 pb-3 row border-bottom align-items-center">
                            <label for="" class="control-label text-md-end col-md-3">Année Académique</label>
                            <div class="col-md-6">
                                <select class="form-select mr-sm-2 p-2" id="acadYear" name="acadYear">
                                    <option value="{{ Session::get('RESULTAT_DATA')['RESULTAT_YEAR']->annee_acad }}">
                                        {{ Session::get('RESULTAT_DATA')['RESULTAT_YEAR']->periode }}
                                    </option>
                                </select>
                            </div>
                        </div>
                        <div class="mb-3 pb-3 row border-bottom align-items-center">
                            <label for="" class="control-label text-md-end col-md-3">Niveau formation</label>
                            <div class="col-md-6">
                                <select class="form-select mr-sm-2 p-2" id="formation" name="formation">
                                    @foreach ($data['formations'] as $formation)
                                        <option value="{{ $formation->id }}">{{ $formation->niveauFormation }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="mb-3 pb-3 row border-bottom align-items-center">
                            <label for="" class="control-label text-md-end col-md-3">Année d'Etude</label>
                            <div class="col-md-6">
                                <select class="form-select mr-sm-2 p-2" id="etudeYear" name="etudeYear">
                                    <option>Sélectionner l'année d'étude</option>
                                    @foreach ($data['etudes'] as $etude)
                                        <option value="{{ $etude->id }}">{{ $etude->annee_etude }}</option>
                                    @endforeach
                                </select>
                                <div class="invalid-feedback">
                                    L'année d'étude est requise
                                </div>
                            </div>
                        </div>
                        <div class="mb-3 pb-3 row border-bottom align-items-center">
                            <label for="" class="control-label text-md-end col-md-3">{{ $data['label'] }}</label>
                            <div class="col-md-6">
                                <select class="select2 p-2 select2-data-array" style="width: 100%"
                                    id="{{ $data['input_name'] }}" name="{{ $data['input_name'] }}">
                                </select>
                                <div class="invalid-feedback">
                                    {{ $data['validation'] }}
                                </div>
                            </div>
                        </div>
                        <div class="mb-3 pb-3 row border-bottom align-items-center">
                            <label for="" class="control-label text-md-end col-md-3 align-self-start">Choisir un
                                fichier</label>
                            <div class="col-md-6">
                                <input type="file" id="input-file-events validatedCustomFile" class="dropify"
                                    data-max-file-size="2M"
                                    accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                                    name="file" />
                            </div>
                        </div>
                        <div class="form-actions">
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="row justify-content-center">
                                        <button type="submit"
                                            class="col-4 col-md-2 col-sm-3 col-lg-1 me-3 btn btn-success"> <i
                                                class="fa fa-check"></i> Submit</button>
                                        <button type="reset" class="col-4 col-md-2 col-sm-3 col-lg-1 me-3 btn "
                                            style="background-color: #e4e7ea">Cancel</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('scripts')
    <script src="{{ asset('assets/libs/dropzone/dist/min/dropzone.min.js') }}"></script>
    <script src="{{ asset('assets/libs/select2/dist/js/select2.full.min.js') }}"></script>
    <script src="{{ asset('assets/libs/select2/dist/js/select2.min.js') }}"></script>
    <script src="{{ asset('dist/js/pages/forms/select2/select2.init.js') }}"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.4.29/dist/sweetalert2.all.min.js"></script>

    <script src="{{ asset('dist/js/dropify.min.js') }}"></script>
    <script src="{{ asset('assets/extra-libs/toastr/dist/build/toastr.min.js') }}"></script>
    <script src="{{ asset('assets/extra-libs/toastr/toastr-init.js') }}"></script>

    <script>
        $(document).ready(function() {
            $('.dropify').dropify();

            $('.dropify-fr').dropify({
                messages: {
                    default: 'Glissez-déposez un fichier ici ou cliquez',
                    replace: 'Glissez-déposez un fichier ou cliquez pour remplacer',
                    remove: 'Supprimer',
                    error: 'Désolé, le fichier trop volumineux'
                }
            });

            var drEvent = $('#input-file-events').dropify();
            drEvent.on('dropify.beforeClear', function(event, element) {
                return confirm("Do you really want to delete \"" + element.file.name + "\" ?");
            });
            drEvent.on('dropify.afterClear', function(event, element) {
                alert('File deleted');
            });
            drEvent.on('dropify.errors', function(event, element) {
                console.log('Has Errors');
            });
            var drDestroy = $('#input-file-to-destroy').dropify();
            drDestroy = drDestroy.data('dropify')
            $('#toggleDropify').on('click', function(e) {
                e.preventDefault();
                if (drDestroy.isDropified()) {
                    drDestroy.destroy();
                } else {
                    drDestroy.init();
                }
            });
        });

        $(() => {
            let request = async () => {
                if (!(isNaN($("#filiere").val()) || isNaN($("#acadYear").val()) || isNaN($(
                            "#formation").val()) ||
                        isNaN($("#etudeYear").val()))) {
                    $(".select2-data-array").empty().trigger('change');
                    let url = "{{ $data['mode'] != 'U' ? route('ec.ue') : route('ue') }}";
                    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({
                            idFiliere: $("#filiere").val(),
                            acad_year: $("#acadYear").val(),
                            formation: $("#formation").val(),
                            etude_year: $("#etudeYear").val(),
                            traite: true,
                        }),
                    };

                    @if ($data['mode'] != 'U')
                        await fetch(url, options)
                            .then((response) => response.json())
                            .then((response) => {
                                if (response.success) {
                                    let data = response.data;
                                    if (data.length) {
                                        let selectData = [];
                                        for (let semestre in data.ues) {
                                            selectData.push({
                                                text: '============================== Semestre ' +
                                                    semestre +
                                                    ' ==============================',
                                                children: [{
                                                    id: undefined,
                                                    text: `ECs non renseignés... : ${data.count[semestre]} / ${data.total[semestre]}`,
                                                    disabled: true
                                                }]
                                            });
                                            for (let ue in data.ues[semestre]) {
                                                let ecue = [];
                                                for (let ec in data.ues[semestre][ue]) {
                                                    ecue.push({
                                                        id: ec,
                                                        text: data.ues[semestre][ue][ec]
                                                    });
                                                }
                                                selectData.push({
                                                    text: ue,
                                                    children: ecue
                                                });
                                            }
                                        }
                                        $(".select2-data-array").select2({
                                            placeholder: "{{ $data['placeholder'] }}",
                                            pagination: {
                                                "more": true
                                            },
                                            data: selectData
                                        });
                                    } else
                                        toaster("warning", "Pas d'EC pour les données saisies.");
                                } else
                                    toaster("warning",
                                        "Erreur de connection, veuillez recharger la page.");
                            })
                            .catch((e) => {
                                toaster("error",
                                    "Une erreur est survenue, veuillez recharger la page.");
                            });
                    @else
                        await fetch(url, options)
                            .then((response) => response.json())
                            .then((response) => {
                                if (response.success) {
                                    let data = response.data;
                                    if (data.length) {
                                        let selectData = [];
                                        for (let semestre in data.ues) {
                                            let ues = [];
                                            ues.push({
                                                id: undefined,
                                                text: `UEs non renseignés... : ${data.count[semestre]} / ${data.total[semestre]}`,
                                                disabled: true
                                            });
                                            for (let ue in data.ues[semestre]) {
                                                ues.push({
                                                    id: ue,
                                                    text: data.ues[semestre][ue]
                                                });
                                            }
                                            selectData.push({
                                                text: '============================== Semestre ' +
                                                    semestre +
                                                    ' ==============================',
                                                children: ues
                                            });
                                        }
                                        $(".select2-data-array").select2("destroy");
                                        $(".select2-data-array").select2({
                                            placeholder: "Choisir un élément constitutif",
                                            pagination: {
                                                "more": true
                                            },
                                            data: selectData
                                        });
                                    } else
                                        toaster("warning", "Pas d'UE pour les données saisies.");
                                } else
                                    toaster("warning",
                                        "Erreur de connection, veuillez recharger la page.");
                            })
                            .catch((e) => {
                                console.log(e)
                                toaster("error",
                                    "Une erreur est survenue, veuillez recharger la page.");
                            });
                    @endif
                }
            };
            $('#filiere').change(request);
            $('#acadYear').change(request);
            $('#formation').change(request);
            $(
                '#etudeYear').change(request);

            $(".select2-data-array").select2({
                placeholder: "{{ $data['placeholder'] }}",
                language: {
                    noResults: () => "Traitement tableau de spécification en cours..."
                },
                allowClear: true
            });
            @if ($data['mode'] != 'U')
                $('#submit').submit((e) => {
                    if (![checkValidation('#operation'),
                            checkValidation('#filiere'),
                            checkValidation('#acadYear'),
                            checkValidation('#formation'),
                            checkValidation('#etudeYear'),
                            checkValidation('#ec')
                        ].every(value => value === true)) {
                        e.preventDefault();
                    }
                });
            @else
                $('#submit').submit((e) => {
                    if (![checkValidation('#operation'),
                            checkValidation('#filiere'),
                            checkValidation('#acadYear'),
                            checkValidation('#formation'),
                            checkValidation('#etudeYear'),
                            checkValidation('#ue')
                        ].every(value => value === true)) {
                        e.preventDefault();
                    }
                });
            @endif
        });
        @if (Session::get('noData'))
            {
                let title = '<p>Aucun étudiant n\'est inscrit dans la filière : <span style="color:red">';
                title += "{{ Session::get('intituleFilieres') }}";
                title +=
                    '</span> </p> <p>Ou</p> <p>Vous ne pouvez pas continuer une insertion de notes pour: <span style="color:red">';
                title += "{{ Session::get('intituleUE') }}";
                title += '</span>. Certainement tous les étudiants ont validés cette UE';
                title += "</p>";
                Swal.fire({
                    icon: 'error',
                    title: 'Oops...',
                    html: title
                });
            }
        @endif
        @if (Session::get('insertSuccess'))
            {
                Swal.fire({
                    icon: 'success',
                    title: "{{ Session::get('titleExcel') }}",
                    html: "<p>{!! Session::get('contentex') !!}</p>"
                });
            }
        @elseif (Session::get('errorExcel')) {
                Swal.fire({
                    icon: 'error',
                    title: "{{ Session::get('extitle') }}",
                    html: "<p>{!! Session::get('exmessage') !!}</p>"
                });
            }
        @endif
    </script>
@endsection
