
@extends("layouts.site" , ["useJquery" => true])

@section("title", "Upload")

@section("after_css")
    <link rel="stylesheet" href="{{mix('/css/pages/upload.css')}}">
    <meta name="csrf-token" content="{{ csrf_token() }}" />
@stop

@section("after_js")
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
    <script src="/js/jquery.validate.min.js"></script>
    <script type="text/javascript">
        var oldDocumentId = null;
        var oldMemberListFileId = null;
        var messages = {
            name: "",
            email: "<p class='aantal'><img class='img-email' src='/img/icons/Icon-material-error.png'>  Voer hier a.u.b. een geldig e-mailadres in (bijv. mail@voorbeeld.nl)</p>",
            contactPerson: ""
        };


        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $.validator.addMethod("nameRequired", function(value, element){
           return value && value.length > 0
        }, function(){
            return messages.name
        });

        $.validator.addMethod("contactPerson", function(value, element){
            return value && value.length > 0
        }, function(){
            console.log(messages.contactPerson);
            return messages.contactPerson
        });

        $.fn.serializeFormJSON = function () {

            var o = {};
            var a = this.serializeArray();
            $.each(a, function () {
                if (o[this.name]) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        };

        var type = 1;
        var documentFileId = null;
        var memberListFileId = null;

        function radioClicked(t){
            type = t;
            var buttons = document.querySelectorAll("#gpBtn button");
            for(var i =0; i< buttons.length; i++){
                buttons[i].classList.remove("activeW")
            }

            document.querySelector(type == 0 ? "#btnOne" : "#btnTwo").classList.add("activeW");

            if(type == 1){
                messages.name= "<p class='aantal'><img src='/img/icons/Icon-material-error.png'> Voer hier a.u.b. de naam van de VvE in</p>";
                messages.contactPerson= "<p class='aantal'><img class='img-email' src='/img/icons/Icon-material-error.png'> Voer hier a.u.b. de naam van een contactpersoon in</p>";

            } else {
                messages.name= "<p class='aantal'><img src='/img/icons/Icon-material-error.png'> Voer hier a.u.b. de naam van de beheerder in</p>";
                messages.contactPerson= "<p class='aantal'><img class='img-email' src='/img/icons/Icon-material-error.png'> Voer hier a.u.b. de naam van een contactpersoon in</p>";
            }
            document.querySelector("#nameLabelChange").innerHTML = type == 0 ? 'Naam beheerder <span>*</span>' : 'Naam VvE <span>*</span>';
        }
        radioClicked(1);

        function alertError(err){
            Swal.fire({
                icon: 'error',
                title: '',
                text: err
            })
        }


        $( "#signupForm" ).validate({
            onfocusout: function(element){
                $(element).valid();
            },
            rules: {
                name: {
                    nameRequired: true
                },
                email: {
                    required: true,
                    email: true
                },
                contactPerson: {
                    contactPerson: true
                },
            },
            messages: {
                email: messages.email
            },
            errorElement: "em",
            errorPlacement: function ( error, element ) {
                error.addClass( "invalid-feedback" );
                if ( element.prop( "type" ) === "checkbox" ) {
                    error.insertAfter( element.next( "label" ) );
                } else {
                    error.insertAfter( element );
                }
            },
            highlight: function ( element, errorClass, validClass ) {
                $( element ).addClass("is-invalid").removeClass("is-valid");
            },
            unhighlight: function (element, errorClass, validClass) {
                $( element ).addClass( "is-valid" ).removeClass( "is-invalid" );
            },
            submitHandler: function(form) {
                var data = $(form).serializeFormJSON();

                if(!data.privacy) {
                    alertError("Vink a.u.b. het vakje aan om de bestanden te versturen");
                    return false
                }
                if(documentFileId === null) {
                    alertError("Splitingsakte is niet geupload");
                    return false
                }
                if(memberListFileId === null) {
                    alertError("Ledenlijst is niet geupload");
                    return false
                }

                data.documentId = documentFileId;
                data.memberListId = memberListFileId;
                data.type = type;

                $.post({
                    url: "/api/form/upload",
                    data: data,
                    success: (result)=>{
                        Swal.fire({
                            icon: 'success',
                            title: 'Succesvol verstuurd!',
                            onClose: ()=>{
                                location.href = "/bedankt"
                            }
                        })
                    },
                    error: (err)=> {
                        var errors = "";
                        for (let key in err.responseJSON.errors) {
                            errors += err.responseJSON.errors[key] + "<br/>"
                        }

                        var title = "Dit veld is niet correct ingevuld";
                        if(err.responseJSON.message && !err.responseJSON.message.includes("was invalid")){
                            title = err.responseJSON.message
                        }

                        Swal.fire({
                            icon: "error",
                            title: title,
                            html: errors
                        })
                    },
                    dataType: "json"
                });

                return false
            }

        } );

        var removeSet = [false , false];


        function uploadClicked(which){

            var fileInput = document.getElementById("file-"+which);

            fileInput.click();

            var progress = document.getElementById("progress-"+which);
            progress = progress.querySelector(".bar");
            var box = document.getElementById("box-"+which);

            var removeButton = box.querySelector(".remove-file");

            if(!removeSet[which])
            removeButton.addEventListener("click", function(){
                box.classList.remove("uploading", "uploaded");
                if(which === 0){

                    oldDocumentId = documentFileId;
                    documentFileId = null
                } else {

                    oldMemberListFileId = memberListFileId;
                    memberListFileId = null;
                }
            });
            removeSet[which] = true;

            fileInput.onchange = function(event){
                if(fileInput.files.length){
                    var theFile = fileInput.files[0];
                    var validFormats = ["doc", "docx", "pdf", "xlsx", "xls"];
                    if(Math.round(theFile.size/ 1024) > 5120){
                        alertError("Mag niet groter zijn dan 5MB");
                        return;
                    }
                    var ext = theFile.name.split(".");
                    ext = ext[ext.length-1];
                    var validFormat = false;
                    validFormats.forEach(function(format){
                        if(format === ext)
                            validFormat = true;
                    });

                    if(!validFormat){
                        alertError("Bestandsformaat is niet correct");
                        return;
                    }


                    var formData = new FormData();
                    formData.append("file", fileInput.files[0]);
                    formData.append("oldId", which === 0 ? oldDocumentId : oldMemberListFileId);

                    $.ajax({
                        xhr: function() {
                            box.classList.add("uploading");
                            var xhr = new window.XMLHttpRequest();

                            xhr.upload.addEventListener("progress", function(evt) {
                                if (evt.lengthComputable) {
                                    var percentComplete = evt.loaded / evt.total;
                                    percentComplete = parseInt(percentComplete * 100);
                                    progress.style.width = percentComplete+ "%";

                                    if (percentComplete === 100) {

                                    }

                                }
                            }, false);

                            return xhr;
                        },
                        url: which === 0 ? "/api/upload/document" : "/api/upload/member-list",
                        type: "POST",
                        data: formData,
                        contentType: false,
                        processData: false,
                        cache: false,
                        dataType: "json",
                        success: function(result) {
                            if(which === 0){
                                documentFileId = result.id;
                            } else {
                                memberListFileId = result.id;
                            }
                            box.classList.remove("uploading");
                            box.classList.add("uploaded");
                        },
                        error: function(err){

                            box.classList.remove("uploading");

                            var errors = "";
                            for (let key in err.responseJSON.errors) {
                                errors += err.responseJSON.errors[key] + "<br/>"
                            }

                            var title = "Dit veld is niet correct ingevuld";
                            if(err.responseJSON.message && !err.responseJSON.message.includes("was invalid")){
                                title = err.responseJSON.message
                            }

                            Swal.fire({
                                icon: "error",
                                title: title,
                                html: errors
                            })
                        }
                    });
                }
            }



        }
    </script>

@stop

@section("content")

    <section>
        <div class="box-orange box-blue box-txt-orange">
            <img class="mob-size" src="/img/shared/clouds-white.svg" alt="">
            <img class=" bulding-svg" src="/img/shared/city-white.svg" alt="">
            <h1 style="margin-top: 0">Upload</h1>
            <img class="mob-size-city" src="/img/shared/buildings-white.svg" alt="">
        </div>
    </section>
    <section class="tabs-pri">
        <div class="container">
            <div class="cont-form">
                <p class="upper-description">
                    Om uw VvE of beheer aan te melden, hebben wij allereerst uw splitsingsakte en ledenlijst nodig. <br/>
                    Op deze wijze kunnen wij de app inrichten voor al uw leden.
                </p>


                    <div class="border-bottom">
                        <div class="form-group row">
                            <div class="col-md-4">
                                <label class="lab" for="gpBtn">Maak uw keuze:</label>
                            </div>
                            <div class="col-md-8">
                                <div class="btn-gp" id="gpBtn">
                                    <button id="btnTwo" onclick="radioClicked(1)" class="btn-form activeW">VvE</button>
                                    <button id="btnOne" onclick="radioClicked(0)" class="btn-form">VvE beheerder</button>

                                </div>
                            </div>


                        </div>
                    </div>
                <form id="signupForm" class="form-horizontal">
                    @csrf

                    <div class="form-group row">
                        <label class="col-md-4 col-form-label box-txt-upload" for="lastname" id="nameLabelChange">Naam VvE <span>*</span></label>
                        <div class="col-md-8">
                            <input type="text" class="form-control" id="lastname" name="name" placeholder="" />
                        </div>
                    </div>

                    <div class="form-group row">
                        <label class="col-md-4 col-form-label box-txt-upload" for="Aantal">Naam contactpersoon<span>*</span></label>
                        <div class="col-md-8">
                            <input type="text" class="form-control" id="Aantal" name="contactPerson" placeholder="" />
                        </div>
                    </div>

                    <div class="form-group form-email row">
                        <label class="col-md-4 col-form-label box-txt-upload" for="email">E-mail <span>*</span></label>
                        <div class="col-md-8">
                            <input type="text" class="form-control" id="email" name="email" placeholder="" />
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="upload-part">
                                <div class="title">Splitingsakte</div>
                                <div class="upload-box" id="box-0">
{{--                                    <img src="/img/upload/upload-cloud.svg"/>--}}
{{--                                    <div class="desc">Sleep uw bestand hierin om up te loaden</div>--}}
                                    <button onclick="uploadClicked(0)" type="button">UPLOADEN</button>
                                    <div class="progress" id="progress-0">
                                        <div class="bar"></div>
                                    </div>
                                    <div class="max">Maximaal 5MB</div>
                                    <div class="supported">Ondersteunde formaten onder andere, PDF, Excel, Word</div>

                                    <div class="upload-success">
                                        <img src="/img/upload/upload-done.svg"/>
                                        <div class="desc" style="text-transform: uppercase">Succesvol geupload</div>
                                        <button class="remove-file" type="button">VERWIJDER</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="upload-part">
                                <div class="title">Ledenlijst</div>
                                <div class="upload-box" id="box-1">
{{--                                    <img src="/img/upload/upload-cloud.svg"/>--}}
{{--                                    <div class="desc">Sleep uw bestand hierin om up te loaden</div>--}}
                                    <button onclick="uploadClicked(1)" type="button">UPLOADEN</button>
                                    <div class="progress" id="progress-1">
                                        <div class="bar"></div>
                                    </div>
                                    <div class="max">Maximaal 5MB</div>
                                    <div class="supported">Ondersteunde formaten onder andere, PDF, Excel, Word</div>

                                    <div class="upload-success">
                                        <img src="/img/upload/upload-done.svg"/>
                                        <div class="desc" style="text-transform: uppercase">Succesvol geupload</div>
                                        <button class="remove-file" type="button">VERWIJDER</button>
                                    </div>
                                </div>
                            </div>

                        </div>
                    </div>
                    <div style="height: 40px"></div>

                    <div class="row">
                        <div class="col-md-4"></div>
                        <div class="col-md-5">
                            <div class="privacy">
                                <input type="checkbox" name="privacy"/>
                                <span>
                                    Uw gegevens worden bij ons veilig verstuurd via een SSL verbinding. Verstrekte gegevens aan Appartement worden nimmer aan derden doorgegeven of voor commerciële doeleinden gebruikt.
                                    Lees meer over onze <a href="{{$privacyLink}}" target="_blank">privacyverklaring</a>.
                                    Met het versturen van dit formulier gaat u akkoord met onze <a target="_blank" href="{{$termsConditionsLink}}">Algemene Voorwaarden</a>.
                                </span>
                            </div>

                        </div>
                        <div class="col-md-3">
                            <div class="secure-connection">veilige verbinding</div>
                            <button class="submit-button goto-button" type="submit">VERSTUREN <i class="fa fa-arrow-circle-right"></i> </button>
                        </div>
                    </div>


                </form>


            </div>
        </div>


        <input type="file" id="file-0" style="display: none" name="document-file" multiple="false"
               accept=".doc,.docx,.pdf,.xlsx,.xls"/>
        <input type="file" id="file-1" style="display: none" name="members-file" multiple="false"
               accept=".doc,.docx,.pdf,.xlsx,.xls"/>
    </section>
@stop
