@extends("app.layout.base")

@section("title")
    Booking Liste
@endsection

@section("content")
    <style>
        option {
            color: black;
        }
    </style>
    <main class="justify-unset">
        <h1 class="text-center sde-blue mb-0">{{__('msg.bookingliste')}}</h1>
        {!! session()->get('ReservationExists') !!}
        <div class="col w-100 mt-1">
            <div class="calendar-container">
                <div class="calendar-container__header">
                    <button id="week-previous" class="calendar-container__btn fas fa-arrow-left" title="Previous">
                        <i class="icon ion-ios-arrow-back"></i>
                    </button>
                    <h2 id="title" class="calendar-container__title">{Måned} {År}</h2>
                    <button id="week-next" class="calendar-container__btn fas fa-arrow-right" title="Next">
                        <i class="icon ion-ios-arrow-forward"></i>
                    </button>
                </div>
                <div class="calendar-container__body">
                    <div id="calendar" class="calendar-table">
                        <div class="calendar-table__body">
                        </div>
                    </div>
                </div>
            </div>
            <form method="post" action="{{ route("washing-reservations.store") }}" id="event-container" class="events-container">
                @csrf
            </form>
            @if(count(\App\WashingMachine::all()) < 1)
                <p style="margin: 0 18px;">{{__('msg.dereringenvaskemaskiner')}}.</p>
            @endif
        </div>
    </main>
@endsection

@section("scripts")
    <script src="{{ asset("/js/moment-with-locales.min.js") }}"></script>
    <script src="{{ asset("/js/da.min.js") }}"></script>
    <script>
        //Global vars to use outside functions
        var momentDate = null;
        var dateText = null;

        //Custom forEach
        NodeList.prototype.forEach = Array.prototype.forEach;

        //Generates the calender when the site loads
        function generateCalendar(weekOffset = 0) {
            const week = (moment().week() + weekOffset);

            let weekDays = Array.apply(null, Array(7)).map((value, index) => {
                return moment(index, "e").locale("da").startOf("week").weekday(index).format("ddd");
            });

            document.getElementById("title").innerHTML = '{{__('msg.ugestor')}} ' + moment().locale("da").day(weekDays[0]).week(week).isoWeek().toString();

            const calendar = document.getElementById("calendar");

            let header = document.createElement("div");
            header.classList.add("calendar-table__header", "calendar-table__row");

            let calendarBody = document.createElement("div");
            calendarBody.classList.add("calendar-table__body");

            let calendarRow = document.createElement("div");
            calendarRow.classList.add("calendar-table__row")
            calendarRow.id = "calenderRow";

            //Generate day buttons
            weekDays.forEach(function (weekDay) {
                let headerDay = document.createElement("div");
                headerDay.classList.add("calendar-table__col");

                headerDay.innerText = weekDay;

                header.appendChild(headerDay);

                let date = moment().locale("da").day(weekDay).week(week);
                var datetext = moment().locale("da").day(weekDay).week(week).year() + "-" + prependZero((moment().locale("da").day(weekDay).week(week).month() + 1)) + "-" + prependZero(moment().locale("da").day(weekDay).week(week).date());

                let dayHolder = document.createElement("div");
                dayHolder.classList.add("calendar-table__col");

                let day = document.createElement("div");
                day.classList.add("calendar-table__item");
                day.innerText = date.date();

                //If any date is selected, Add selected class to the selected day
                if(momentDate !== null)
                    if(date.diff(momentDate, 'hours') == 0)
                        dayHolder.classList.add("selected");

                dayHolder.appendChild(day);

                //If date hasn't already happened
                if(date > moment().subtract(1, "days").locale("da")) {
                    //When clicking on a date run "onDateSelect()"
                    dayHolder.onclick = function () {
                        onDateSelect(date, dayHolder, datetext);
                    }
                }
                else
                {
                    dayHolder.classList.add("disabled");
                }

                calendarRow.appendChild(dayHolder);
            });

            calendarBody.appendChild(calendarRow);

            calendar.innerHTML = "";

            calendar.appendChild(header);
            calendar.appendChild(calendarBody);
        }

        //When a date is selected
        function onDateSelect(date, dayHolder, datetext) {
            //Set selected date and dateText
            momentDate = date;
            dateText = datetext;

            //Add selected class on the selected date and remove it on all others
            var children = document.getElementById("calenderRow").childNodes;

            children.forEach(function(item){
                item.classList.remove("selected");
            });

            dayHolder.classList.add("selected");

            /***************/
            /*Generate form*/
            /***************/

            let machine_id;
            let location_id;

            //If a washing-machine select exists, set machine_id to its currently selected options value
            //Else set it to 0
            if(document.getElementById('washing-machines')) {
                machine_id = document.getElementById('washing-machines').value;
            }
            else {
                machine_id = 0;
            }

            //If a location select exists, set location_id to its currently selected options value
            //Else set it to 0
            if(document.getElementById('locations')) {
                location_id = document.getElementById('locations').value;
            }
            else {
                location_id = 0;
            }

            axios({
                method: 'get',
                url: '{{ route("washing-reservations.api") }}',
                params: { 'date': date, 'machine_id': machine_id, 'datetext': datetext, 'location_id': location_id }
            })
                .then(function (response) {
                var data = response.data;

                //Fill locations
                fillLocations(data["locations"], location_id);

                updateForm();
            });
        }

        //Fill locations
        function fillLocations(locations, selected_location_id){
            var element;

            //If a location select exists, set element to the select element
            //Else create it
            if(document.getElementById("locations") !== null) {
                element = document.getElementById("locations");

                //Clear locations
                element.innerHTML = "";
            }
            else {
                let span = document.createElement("span");
                span.classList.add("events__title");
                span.innerText = "{{__('msg.lokation')}}";

                let select = document.createElement("select");
                select.classList.add("events__title");
                select.id = "locations";
                select.name = "location_id";

                select.onchange = function() {
                    updateForm();
                }

                document.getElementById("event-container").appendChild(span);
                document.getElementById("event-container").appendChild(select);

                element = document.getElementById("locations");
            }

            element.onchange = function () {
                updateForm();
            }

            //Add location options
            for (let i = 0; i < locations.length; i++) {
                let option = document.createElement("option");
                option.text = locations[i]["name"];
                option.value = locations[i]["id"];

                //If current location is the location we have selected, mark it selected
                if(selected_location_id == locations[i]["id"])
                    option.selected = "selected";

                element.appendChild(option);
            }
        }

        //Fill washing-machines
        function fillMachines(machines, selected_machine_id) {
            var element;

            //If a washing-machine select exists, set element to the select element
            //Else create it
            if(document.getElementById("washing-machines") !== null) {
                element = document.getElementById("washing-machines");

                //Clear machines
                element.innerHTML = "";
            }
            else {
                let span = document.createElement("span");
                span.classList.add("events__title");
                span.innerText = "{{__('msg.maskiner')}}";

                let select = document.createElement("select");
                select.classList.add("events__title");
                select.id = "washing-machines";
                select.name = "machine_id";

                select.onchange = function() {
                    updateForm();
                }

                document.getElementById("event-container").appendChild(span);
                document.getElementById("event-container").appendChild(select);

                element = document.getElementById("washing-machines");
            }


            element.onchange = function () {
                updateForm();
            }

            //Add machine options
            for (let i = 0; i < machines.length; i++) {
                let option = document.createElement("option");
                option.text = machines[i]["name"];
                option.value = machines[i]["id"];

                //If current machine is the machine we have selected, mark it selected
                if(selected_machine_id == machines[i]["id"])
                    option.selected = "selected";

                element.appendChild(option);
            }
        }

        //Fill events (times) and remove unavailable_times
        function fillTimes(unavailable_times, datetext, date) {
            var element;

            //If a events (times) select exists, set element to the select element
            //Else create it
            if(document.getElementById("events") !== null) {
                element = document.getElementById("events");

                //Clear times
                element.innerHTML = "";
            }
            else {
                let span = document.createElement("span");
                span.classList.add("events__title");
                span.innerText = "{{__('msg.tilgængeligetider')}}";

                let select = document.createElement("select");
                select.classList.add("events__title");
                select.id = "events";
                select.name = "time";

                document.getElementById("event-container").appendChild(span);
                document.getElementById("event-container").appendChild(select);

                element = document.getElementById("events");
            }


            //Add times 8:00-20:00
            for (let hour = 8; hour < 20; hour++) {
                if(hour < new Date().getHours() && moment().locale("da").diff(date, 'hours') == 0)
                    continue;

                let value = datetext + " " + prependZero(hour) + ":00:00";

                let option = document.createElement("option");

                option.text = prependZero(hour) + ":00-" + prependZero(hour+1) + ":00";
                option.value = value;
                option.id = value;
                element.appendChild(option);
            }

            //Remove unavailable_times
            unavailable_times.forEach(function (item, index) {
                document.getElementById(item).remove();
            });

            //If a submit button doesn't exist, create it
            if(document.getElementById("create-reservation") === null) {
                let button = document.createElement("button");

                button.id = "create-reservation";
                button.innerText = "{{__('msg.reserver')}}";
                button.classList.add("btn", "btn-sde-blue")
                button.type = "submit";

                document.getElementById("event-container").appendChild(button);
            }

            //If there is no available times, disable the make reservation button and create new option
            if(element.childElementCount === 0){
                let option = document.createElement("option");
                option.disabled = "disabled";
                option.text = "Der er ingen tilgængelige tider";
                option.selected = "selected";
                element.appendChild(option);

                document.getElementById("create-reservation").disabled = "disabled";
            }
            else {
                document.getElementById("create-reservation").disabled = "";
            }
        }

        //Update selects
        function updateForm() {
            //console.log("Updating form...");
            var location_id;
            var machine_id;

            //If a location select exists, set location_id to its currently selected options value
            //Else set it to 0
            if(document.getElementById('locations') !== null)
                location_id = document.getElementById('locations').value;
            else
                location_id = 0;

            //console.log("location_id: " + location_id);

            //If a washing-machine select exists, set machine_id to its currently selected options value
            //Else set it to 0
            if(document.getElementById('washing-machines') !== null)
                machine_id = document.getElementById('washing-machines').value;
            else
                machine_id = 0;

            axios({
                method: 'get',
                url: '{{ route("washing-reservations.getMachines") }}',
                params: { 'location_id': location_id }
            })
                .then(function (response) {
                    var data = response.data;

                    //Fill washing-machines
                    fillMachines(data["washingmachines"], machine_id);

                    //If a washing-machine select exists, set machine_id to its currently selected options value
                    //Else set it to 0
                    if(document.getElementById('washing-machines') !== null)
                        machine_id = document.getElementById('washing-machines').value;
                    else
                        machine_id = 0;

                    //console.log("machine_id: " + machine_id);

                    axios({
                        method: 'get',
                        url: '{{ route("washing-reservations.getTimes") }}',
                        params: { 'machine_id': machine_id, 'datetext': dateText }
                    })
                        .then(function (response) {
                            var data = response.data;

                            //Fill events (times) and remove unavailable_times
                            fillTimes(data["unavailable_times"], dateText, momentDate);
                        });
                });
        }

        //Adds a "0" in front of values below 10
        function prependZero(value) {
            if(value < 10)
                return "0" + value;
            return value;
        }

        //The offset from the current week
        let weekOffset = 0;
        var styleElem = document.head.appendChild(document.createElement("style"));
        styleElem.innerHTML = "#week-previous:before {color: unset;}";

        //Generate calender and set onclick function on the week changing arrows
        if(document.getElementById("calendar")) {
            generateCalendar();

            document.getElementById("week-previous").onclick = function () {
                if(weekOffset > 0)
                {
                    weekOffset--;
                    if(weekOffset == 0){
                        styleElem.innerHTML = "#week-previous:before {color: unset;}";
                    }
                    generateCalendar(weekOffset);
                }
            }

            document.getElementById("week-next").onclick = function () {
                if(weekOffset == 0)
                {
                    styleElem.innerHTML = "#week-previous:before {color: black;}";
                }
                weekOffset++;
                generateCalendar(weekOffset);
            }
        }
    </script>
@endsection