@extends('layouts.base')

@section('title', 'Starter Page')

@section('css')
    {{-- include page's specific styles here  --}}
@endsection

@section('content')
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-info p-4">
                    <h4 class="mb-0 text-white">Veuillez sélectionner les données s'il vous plait.</h4>
                </div>
                <div class="card-body">
                    <form enctype="multipart/form-data" method="get" id="fmanuelle" class="form-horizontal form-bordered"
                        onsubmit="return false;">
                        <div class="form-body">
                            <div class="form-group mb-3 pb-3 border-bottom  row align-items-center">
                                <label class="control-label text-md-end col-md-3">Nom & Prénom</label>
                                <div class="col-md-6">
                                    <select name="nom_prenom" id="matricule" class="form-select"
                                        data-placeholder="Rechercher un étudiant...">
                                        <option
                                            value="{{ $data['matricule'] . '-' . $data['filiere']->idFiliere . '-' . $data['annee'] . '-' . $data['niveau'] . '-' . $data['year']->annee_acad }}">
                                            {{ $data['nomPrenom'] }}</option>
                                    </select>

                                </div>
                            </div>
                            <div class="form-group mb-3 pb-3 border-bottom  row align-items-center">
                                <label class="control-label text-md-end col-md-3">Filière</label>
                                <div class="col-md-6">
                                    <select name="idFiliere" id="idFiliere" class="form-select" required>
                                        <option value="{{ $data['filiere']->idFiliere }}">
                                            {{ $data['filiere']->intituleFilieres }}({{ $data['filiere']->sigleFilieres }})
                                        </option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group mb-3 pb-3 border-bottom  row align-items-center">
                                <label class="control-label text-md-end col-md-3">Année Académique</label>
                                <div class="col-md-6">
                                    <select name="academique" id="academique" class="form-select" required>
                                        <option value="{{ $data['year']->annee_acad }}">{{ $data['year']->periode }}
                                        </option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group mb-3 pb-3 border-bottom row align-items-center">
                                <label class="control-label text-md-end col-md-3">Niveau formation</label>
                                <div class="col-md-6">
                                    <select name="niveau" id="niveau" class="form-select">
                                        <?php echo $data['optionNiv']; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group mb-3 pb-3 border-bottom  row align-items-center">
                                <label class="control-label text-md-end col-md-3">Année d'Etude</label>
                                <div class="col-md-6">
                                    <select name="annee" id="annee" class="form-select">
                                        <?php echo $data['optionAnn']; ?>
                                    </select>
                                </div>
                            </div>

                            <div class="form-group mb-3 pb-3 row align-items-center">
                                <label class="control-label text-md-end col-md-3">Référence dossier</label>
                                <div class="col-md-6">
                                    <input name="group-ref" id="refFacture" type="text" value="<?php echo $data['matricule']; ?>"
                                        readonly class="form-control">
                                </div>
                            </div>
                        </div>

                        <div style="border-top: solid 1px rgba(0,0,0,0.1); padding-top:15px; ">
                            <div class="butt" style="width: 100%;margin: auto;">
                                <button class="btn btn-success" onclick="manuel()"><i class="fa fa-check"></i>
                                    Submit</button>
                                <button type="reset" class="btn"
                                    style="background: #e4e7ea; border:#e4e7ea;height:36px" id="cancel">Cancel</button>
                                <button class="btn btn-danger" type="button" id="takescan"><i
                                        class="fa fa-check-circle"></i>Scanner</button>
                            </div>
                        </div>
                    </form>

                    <div class="" id="divscan" style="display:none;">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="card" style="margin: 20px 0px;">
                                    <div class="card-header bg-info">
                                        <h3 class="">Veuillez scanner le dossier SVP!</h3>
                                    </div>
                                    <div class="card-body">

                                        <form id="form1" action="" method="post" target="_blank"
                                            style="display: flex;flex-direction:column;gap:30px">
                                            <div class="form-group">
                                                <label for="sample-field-1">INFO:</label>
                                                Avec ce formulaire, vous avez la possibilité de scanner en image au
                                                format
                                                JPG le reçu de la banque apporté par l'étudiant.
                                                Mais avant de l'utiliser veuillez d'abord installer ce composant <a
                                                    href="https://www.neodynamic.com/downloads/jspm/"
                                                    target="_blank">téléchargeable
                                                    ici</a>.
                                                Puis scanner le reçu en cliquant tout simplement sur le bouton bleu "Scan".
                                            </div>
                                            <label>Scanner:</label>
                                            <select id="scannerName"></select>
                                            <div style="width: 100%;">
                                                <div class="res">
                                                    <label>Resolution (DPI):</label>
                                                    <input type="text" id="resolution" value="200" />
                                                </div>
                                                <div class="pix">
                                                    <label>Pixel Mode:</label>
                                                    <select id="pixelMode">
                                                        <option>Grayscale</option>
                                                        <option selected>Color</option>
                                                    </select>
                                                </div>
                                                <div class="format">
                                                    <label>Image Format:</label>
                                                    <select id="imageFormat">
                                                        <option selected>JPG</option>
                                                        <option>PNG</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="form-group">
                                                <label for="sample-field-1">Référence opération:</label>
                                                <div>
                                                    <input name="refFacture2" id="refFacture2" type="text"
                                                        style="background-color: #eee; opacity:1"
                                                        value="<?php echo $data['matricule']; ?>" readonly="" class="form-control">
                                                </div>
                                            </div>

                                            <div class="form-group">
                                                <label>Documents (à numériser) <a href="javascript:clearScans();"
                                                        onclick="clearScan();"><span style="font-weight: normal;">Clear
                                                            scans</span></a></label>

                                                <div>
                                                    <button type="button" class="btn btn-xs btn-info"
                                                        onclick="doScanning();">Scan
                                                        as JPG or PNG</button>
                                                    <button type="button" id="fermer" class="btn btn-xs btn-danger">
                                                        <i class="fa fa-check-circle"></i> Fermer</button>
                                                    <input type="button" class="btn btn-xs btn-primary"
                                                        value="Save image" onclick="submitForm1();"
                                                        style="float: right;">
                                                </div>
                                            </div>
                                            <div id="images" style="margin-left: 0px; margin-top: 10px;"></div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            <div id="info" class="well"
                                style="width:100%; display:block;background-color: #fff; height: 500px; margin-top: 35px; padding: 12px; overflow: scroll !important; border:1px solid black;display:flex;justify-content:center">
                                {{-- <p><i>Information window</i></p>
                        <p class="warn">Currently, only Windows is supported.</p> --}}
                                <img id="scanOutput" alt="image">
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('script')
    {{-- include page's specific scripts here --}}
    <script>
        // -------------- Optional status display, depending on JQuery --------------
        function displayStatus(loading, mesg, clear) {
            if (loading) {
                $('#info').html((clear ? '' : $('#info').html()) +
                    '<p><img src="loading.gif" style="vertical-align: middle;" hspace="8"> ' + mesg + '</p>');
            } else {
                $('#info').html((clear ? '' : $('#info').html()) + mesg);
            }
        }

        // -------------- scanning related code: independent of any 3rd JavaScript library --------------
        function scanAsJpg() {
            displayStatus(true, 'Scanning', true);
            scanner.scan(handleImages, {
                "output_settings": [{
                    "type": "return-base64",
                    "format": "jpg"
                }],
                "i18n": {
                    "lang": getLang()
                }
            }, true, false);
        }

        function scanAsPdf() {
            displayStatus(true, 'Scanning', true);
            scanner.scan(handleImages, {
                "output_settings": [{
                    "type": "return-base64",
                    "format": "pdf"
                }],
                "i18n": {
                    "lang": getLang()
                }
            }, true, false);
        }

        function scanThenUpload() {
            displayStatus(true, 'Scanning', true);
            scanner.scan(handleUploadResponse, {
                "output_settings": [{
                    "type": "upload",
                    "format": "pdf",
                    "pdf_force_black_white": false,
                    "upload_target": {
                        "url": "upload.php?action=dump",
                        "cookies": "name=value; poweredBy=Asprise"
                    }
                }],
                "i18n": {
                    "lang": getLang()
                }
            }, true, false);
        }

        /** Returns true if it is successfully or false if failed and reports error. */
        function checkIfSuccessfully(successful, mesg, response) {
            displayStatus(false, '', true);
            if (successful && mesg != null && mesg.toLowerCase().indexOf('user cancel') >= 0) { // User cancelled.
                displayStatus(false, '<pre>' + "User cancelled." + '</pre>', true);
                return false;
            } else if (!successful) {
                displayStatus(false, '<pre>' + "Failed: " + mesg + "\n" + response + '</pre>', true);
                return false;
            }
            return true;
        }

        /** Callback function to retrieve scanned images. Returns number of images retrieved. */
        function handleImages(successful, mesg, response) {
            if (!checkIfSuccessfully(successful, mesg, response)) {
                return 0;
            }

            var scannedImages = scanner.getScannedImages(response, true, false);
            displayStatus(false, '<pre>' + "Scanned Successfully" + '</pre>', true);
            for (var i = 0;
                (scannedImages instanceof Array) && i < scannedImages.length; i++) {
                var img = scannedImages[i];
                displayStatus(false, "\n<pre>  " + img.toString() + "</pre>", false);
                appendImage(img, document.getElementById('images'));
            }
            return (scannedImages instanceof Array) ? scannedImages.length : 0;
        }

        /** Callback function to retrieve upload response */
        function handleUploadResponse(successful, mesg, response) {
            if (!checkIfSuccessfully(successful, mesg, response)) {
                return 0;
            }

            var uploadResponse = scanner.getUploadResponse(response);
            if (uploadResponse) {
                displayStatus(false, "<h2>Upload Response from the Server Side: </h2>" + uploadResponse, true);
            } else {
                displayStatus(false, '<pre>' + "Failed: " + mesg + "\n" + response + '</pre>', true);
            }
        }

        /** Displays general response to the page - for demo purpose only. */
        function universalHandlerForDemo(successful, mesg, response) {
            try {
                if (!checkIfSuccessfully(successful, mesg, response)) {
                    return;
                }

                // Original images
                var imgCount = handleImages(successful, mesg, response);

                // Thumbnails
                var thumbs = scanner.getScannedImages(response, false, true);
                if (thumbs.length > 0) {
                    displayStatus(false, '<pre>' + "Thumbnails acquired: " + thumbs.length + '</pre>', false);

                    $("#info").append("<div id=\"thumbs\"></div>");

                    for (var i = 0; i < thumbs.length; i++) {
                        var t = thumbs[i];
                        appendImage(t, document.getElementById('thumbs'), true);
                    }
                }

                var saveResponse = scanner.getSaveResponse(response);
                if (saveResponse) {
                    displayStatus(false, "<h2>File Save Result: </h2>" + saveResponse, false);
                }
                var uploadResponse = scanner.getUploadResponse(response);
                if (uploadResponse) {
                    displayStatus(false, "<h2>Upload Response from the Server Side: </h2>" + uploadResponse, false);
                }
            } catch (e) {
                displayStatus(false, "<h2>Exception</h2><p>" +
                    (e == null ? e : e.toString().replace(/[\x26\x0A\<>'"]/g, function(r) {
                        return "&#" + r.charCodeAt(0) + ";"
                    })) +
                    "</p>", false);
            }
        }

        /** To track all the images (thumbnails excluded) scanned so far. */
        /** @type ScannedImage[] */
        var imagesScanned = [];

        /**
         * Appends image to given dom node.
         * @param scannedImage ScannedImage
         * @param domParent
         */
        function appendImage(scannedImage, domParent, isThumbnail) {
            if (!scannedImage) {
                return;
            }
            scanner.logToConsole("Appending scanned image: " + scannedImage.toString());
            if (!isThumbnail) {
                imagesScanned.push(scannedImage);
            }
            if (scannedImage.mimeType == scanner.MIME_TYPE_BMP || scannedImage.mimeType == scanner.MIME_TYPE_GIF ||
                scannedImage.mimeType == scanner.MIME_TYPE_JPEG || scannedImage.mimeType == scanner.MIME_TYPE_PNG) {
                var elementImg = scanner.createDomElementFromModel({
                    'name': 'img',
                    'attributes': {
                        'class': 'scanned zoom thumb thumb-img',
                        'src': scannedImage.src,
                        'height': '100'
                    }
                });
                domParent.appendChild(elementImg);
                // optional UI effect that allows the user to click the image to zoom.
                enableZoom();

            } else if (scannedImage.mimeType == scanner.MIME_TYPE_PDF) {
                var elementA = scanner.createDomElementFromModel({
                    'name': 'a',
                    'attributes': {
                        'href': 'javascript:previewPdf(' + (imagesScanned.length - 1) + ');',
                        'class': 'thumb thumb-pdf'
                    }
                });
                domParent.appendChild(elementA);
            }
        }

        function submitForm1() {
            var matricule = document.getElementById("matricule").value;
            var niveau = document.getElementById("niveau").value;
            var annee = document.getElementById("annee").value;
            var academique = document.getElementById("academique").value;
            var idFiliere = document.getElementById("idFiliere").value;
            var refFacture = document.getElementById("refFacture").value;
            if (matricule == '' || niveau == '' || annee == '' || academique == '' || idFiliere == '' || refFacture == '') {
                alert('Veuillez remplir les champs avant de scanner le recu...');
            } else {
                displayStatus(true, "En cours de soumission, veuillez patienter ...", true);
                if (!scanner.submitFormWithImages('form1', imagesScanned, function(xhr) {
                        if (xhr.readyState == 4) { // 4: request finished and response is ready
                            displayStatus(false, "<h2>Réponse du serveur: </h2>" + xhr.responseText, true);
                        }
                    })) {
                    displayStatus(false, "La soumission du formulaire est annulée. Veuillez d'abord numériser une image.",
                        true);
                }
            }
        }

        function clearScans() {
            if ((imagesScanned instanceof Array) && imagesScanned.length > 0) {
                if (window.confirm("Êtes-vous sûr de vouloir effacer les images numérisées?")) {
                    imagesScanned = [];
                    document.getElementById('images').innerHTML = '';
                }
            }
        }

        function getLang() {
            return $("#lang").val();
        }

        // Low level scanner access demos
        function selectASource() {
            displayStatus(true, 'Sélection d\'une source ...', true);
            scanner.getSource(handleLowLevelApiResponse, "select", true, null, null, false, null, {
                "i18n": {
                    "lang": getLang()
                }
            });
        }

        function listSources() {
            displayStatus(true, 'Listes toutes les sources ...', true);
            scanner.listSources(handleLowLevelApiResponse, false, "all", false, false, null);
        }

        function getSourceCaps() {
            displayStatus(true, 'Gets source capabilities ...', true);
            scanner.getSource(handleLowLevelApiResponse, "select", false, "all", false, true,
                "CAP_FEEDERENABLED: false; ICAP_UNITS: TWUN_INCHES", {
                    "i18n": {
                        "lang": getLang()
                    }
                });
        }

        function getSystemInfo() {
            displayStatus(true, 'Gets system info ...', true);
            scanner.callFunction(handleLowLevelApiResponse, "asprise_scan_system_info");
        }

        function handleLowLevelApiResponse(successful, mesg, result) {
            displayStatus(false, (successful ? "OK" : "ERROR") + '<pre>' + (mesg ? " - " + mesg : "") + "\n" + result +
                '</pre>', true);
        }

        $(function() {
            if (window.scanner.hasJava()) {
                displayStatus(false, "JRE: " + window.scanner.deployJava.getJREs(), false);
            } else {
                if (!window.scanner.isWindows()) {
                    displayStatus(false, "<p class='warn'>Currently, only Windows is supported.</p>", false);
                }
            }
        });
        $("#fermer").click(function() {
            $('#divscan').css('display', 'none');
        });

        $("#takescan").click(function() {
            $('#divscan').css('display', 'block');
        });

        let request = async (data) => {
            let url = "{{ route('set_dossier') }}";
            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({
                    form: data
                }),
            };

            console.log(data[0]['value']);
            await fetch(url, options)
                .then((response) => response.json())
                .then((response) => {
                    if (response.success) {
                        Swal.fire({
                            title: "",
                            text: "Dossier enregistré avec succès!!!",
                            icon: "info",
                            closeOnConfirm: false,
                            confirmButtonClass: "btn-danger",
                            confirmButtonText: "OK",
                            confirmButtonColor: "#ec6c62",
                            showCancelButton: true
                        })
                        $.unblockUI()
                    } else {
                        Swal.fire({
                            title: "<font color = red size=5><i>Erreur dans le traitement de votre requête.</i></font>",
                            text: response.message,
                            type: "error",
                            closeOnConfirm: false,
                            showLoaderOnConfirm: true,
                            confirmButtonClass: "btn-danger",
                            confirmButtonText: "OK",
                            confirmButtonColor: "#ec6c62"
                        })
                        $.unblockUI()
                    }
                })
                .catch((e) => {
                    $.unblockUI()
                    Swal.fire({
                        html: '<font color = red size=5><i>Erreur dans le traitement de votre requête.</i></font>',
                        title: "",
                        text: e,
                        icon: "error",
                        closeOnConfirm: false,
                        showLoaderOnConfirm: true,
                        confirmButtonClass: "btn-danger",
                        confirmButtonText: "OK",
                        confirmButtonColor: "#ec6c62"
                    })
                });
        }
        var manuel = function() {
            $(document).ready(function() {
                data = $("#fmanuelle").serializeArray();
                if ($('#nom_prenom').val() == '' || $('#refFacture').val() == '') {
                    Swal.fire({
                        title: "",
                        text: "Veuillez controler les champs!!!",
                        icon: 'error',
                        closeOnConfirm: false,
                        confirmButtonText: "OK",
                        confirmButtonColor: "#d33"
                    });
                } else {
                    Swal.fire({
                        title: '<font color = red size=5><i>Bien vouloir confirmer cette opération.</i></font>',
                        html: "<b>Scan dossier!!!</b>",
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonColor: '#3085d6',
                        cancelButtonColor: '#d33',
                        cancelButtonText: 'Annuler',
                        confirmButtonText: 'Confirmer!'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            $.blockUI({
                                overlayCSS: {
                                    backgroundColor: 'rgba(255,0,0,0.7)'
                                },
                                centerY: 0,
                                css: {
                                    top: '10px',
                                    left: '',
                                    right: '10px',
                                    border: '3px solid #a00'
                                }
                            });
                            request(data);
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'Cancelled',
                                text: 'Opération annulée... :)',
                                footer: ''
                            })
                        }
                    })
                }
                return false;
            })

        }
    </script>
@endsection
