@extends('layouts.master')
@section('pageTitle') @include('layouts.includes.title', ['moduleTitle' => __('locale.timetable')]) @stop
@section('pageBreadcrumb') @include('layouts.includes.breadcrumb', ['moduleTitle' => __('locale.timetable').' '. __('locale.details') ]) @stop
@section('content')
    <div class="row __sms__datatable">
        <div class="col-lg-9">
            <div class="card card-topline-yellow">
                <div class="card-head">
                    <header>{{ __('locale.timetable')}} </header>
                </div>
                <div class="card-body ">
                    {!! Form::open(['id' => 'timetableForm', 'data-create-url' => route('timetable.store'), 'data-update-url' => route('timetable.update', 'timetableRef')]) !!}
                    {!!  Form::hidden('__ref__id', 0, array("class" => "__ref__id", "id" => "__ref__id", "readonly" => true)) !!}
                    <div class="row">
                        {!!  Form::openGroup('class_id', __('locale.class') ,array("lbl_class" => "required", "class" => 'col-lg-4')) !!}
                        {!!  Form::select('class_id', [null=>__('locale.please_select')] +$data['studentClasses'], '', array("required" => "true", 'id' => '_ref_class_id', 'class'=> 'form-control __change__student__class', 'data-url' => route('class.ajax_on_change', 'classId'),'defaultTxt' => __( 'locale.select' ) ) ) !!}
                        {!!  Form::closeGroup() !!}

                        {!!  Form::openGroup('section_id', __('student::locale.section') ,array("lbl_class" => "required", "class" => 'col-lg-4')) !!}
                        <div class="__replace__section__byClass">
                            {!!  Form::select('section_id', [null=>__('locale.please_select')]+$data["sections"],'', array("required" => "true", 'id' => 'section_id', 'class'=> 'form-control __sms__change__section', 'data-url' => route('division.ajax_on_change'),'defaultTxt' => __( 'locale.select' ) ) ) !!}
                        </div>
                        {!!  Form::closeGroup() !!}

                        {!!  Form::openGroup('class_teacher', __('timetable::locale.class_teacher'), array("class" => 'col-lg-4')) !!}
                        {!!  Form::text('class_teacher', old('class_teacher'), array("class" => "__sms_class_teacher", "readonly" => true)) !!}
                        {!!  Form::closeGroup() !!}

                        {!!  Form::openGroup('week_day', __('timetable::locale.day') ,array("lbl_class" => "required", "class" => 'col-lg-4')) !!}
                        {!!  Form::select('week_day', [null=>__('locale.please_select')] +$data['weekDay'], '', array("required" => "true", 'id' => '_ref_week_day', 'class'=> 'form-control __sms__check__availability','defaultTxt' => __( 'locale.select' ) ) ) !!}
                        {!!  Form::closeGroup() !!}

                        {!!  Form::openGroup('subject_id', __('timetable::locale.subject') ,array("lbl_class" => "required", "class" => 'col-lg-4')) !!}
                        {!!  Form::select('subject_id', [null=>__('locale.please_select')] +$data['subjects'], '', array("required" => "true", 'id' => '_ref_subject_id', 'class'=> 'form-control','defaultTxt' => __( 'locale.select' ) ) ) !!}
                        {!!  Form::closeGroup() !!}

                        {!!  Form::openGroup('teacher_id', __('timetable::locale.teacher') ,array("lbl_class" => "required", "class" => 'col-lg-4')) !!}
                        {!!  Form::select('teacher_id', [null=>__('locale.please_select')] +$data['teachers'], '', array("required" => "true", 'id' => '_ref_teacher_id', 'class'=> 'form-control __sms__check__availability','defaultTxt' => __( 'locale.select' ) ) ) !!}
                        {!!  Form::closeGroup() !!}

                        {!!  Form::openGroup('start_time', __('timetable::locale.start_time'),array("lbl_class" => "required", "class" => 'col-lg-4')) !!}
                        {!!  Form::text('start_time',old('start_time'),["required" => "true", 'id' => '_ref_start_time', "autocomplete" => "off",'class' => 'form-control setTimePicker __sms__change__time']) !!}
                        {!!  Form::closeGroup() !!}

                        {!!  Form::openGroup('end_time', __('timetable::locale.end_time'),array("lbl_class" => "required", "class" => 'col-lg-4')) !!}
                        {!!  Form::text('end_time',old('end_time'),["required" => "true", 'id' => '_ref_end_time', "autocomplete" => "off",'class' => 'form-control setTimePicker __sms__change__time']) !!}
                        {!!  Form::closeGroup() !!}

                        {!!  Form::openGroup('total_time', 'locale.total_time', array("lbl_class" => "required", "class" => 'col-lg-4')) !!}
                        {!!  Form::text('total_time', old('total_time'), ["required" => "true", 'id' => "_ref_total_time","class" => "form-control", 'readonly' => true]) !!}
                        {!!  Form::closeGroup() !!}

                        {!!  Form::openGroup('is_online', 'locale.is_online', array("class" => 'col-lg-4', "style" => "align-self: flex-end;")) !!}
                        {!!  Form::checkbox('is_online', old('is_online'), ['id' => "_ref_is_online","class" => "form-control"]) !!}
                        {!!  Form::closeGroup() !!}

                        {!!  Form::openGroup('grace_period', 'locale.grace_period_to_join', array("lbl_class" => "required", "class" => 'col-lg-4')) !!}
                        {!!  Form::text('grace_period', old('grace_period'), ["required" => "true", 'id' => "_ref_grace_period","class" => "form-control"]) !!}
                        {!!  Form::closeGroup() !!}

                        {!!  Form::openGroup('remark', 'locale.remark', array("class" => 'col-lg-12')) !!}
                        {!!  Form::text('remark', old('remark'), ['id' => "_ref_remark","class" => "form-control"]) !!}
                        {!!  Form::closeGroup() !!}
                        <div class="col-lg-12 form-group col-md-12" id="form-errors"></div>

                        <div class="col-lg-12 form-group col-md-12" style="align-self: flex-end;">
                            <button type="submit"
                                    class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect m-b-10 btn-pink float-right"
                                    id="form-btn-save" data-upgraded=",MaterialButton,MaterialRipple">Save<span
                                    class="mdl-button__ripple-container"><span class="mdl-ripple"></span></span>
                            </button>
                        </div>
                    </div>
                    {!! Form::close() !!}
                </div>
            </div>
        </div>
        <div class="col-lg-3">
            <div class="card card-topline-yellow">
                <div class="card-head">
                    <header>{{ __('locale.availability')}}
                        <i class="fa fa-question-circle" aria-hidden="true"
                           title="Teacher availability for selected date"></i>
                    </header>
                </div>
                <div class="card-body ">

                    <div class=""><div class="col-lg-12"><i class="fa fa-circle is-online-icon" aria-hidden="true"></i> = {{ __('locale.online')}}</div></div>

                    <div class="table-scrollable mt-0">
                        <table id="{{$moduleName}}-table-availability"
                               class="display table table-checkable order-column valign-middle __subject__table mt-0"
                               style="width: 100%">
                            <thead>
                            <tr>
                                <th width="10%"> {{ __('locale.class') }}</th>
                                <th width="15%"> {{ __('locale.time') }}</th>
                            </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-12">
            <div class="card card-topline-yellow">
                <div class="card-body ">

                    <div class="row">

                        <div id="timetableCalendar"></div>

                    </div>
                </div>
            </div>
        </div>
    </div>
@stop
@section('scripts')

    <style>
        .dataTables_wrapper {
            margin-top: 0px;
        }
        .table-scrollable {
            margin: 0 0!important;
        }
        table.dataTable {
            margin-top: 0px !important;
        }

        .is-online{
            background-color: #26c281;
            color: #fff;
        }
        .is-online-icon{
            color: #26c281;
        }
        .fc-event, .fc-event-dot {
            background-color: #1880c9 !important;
        }
        .fc-event .fc-bg {
            opacity: 0 !important;
        }
    </style>
    <link href="{{ asset('assets/plugins/fullcalendar/fullcalendar.css') }}" rel="stylesheet" type="text/css"/>
    <script src="{{ asset('assets/plugins/moment/moment.min.js') }}"></script>
    <script src="{{ asset('assets/plugins/fullcalendar/fullcalendar.min.js') }}"></script>
    <script src="{{ asset('assets/js/pages/calendar/calendar.min.js') }}"></script>

    <link href="{{ asset('assets/plugins/sweet-alert/sweetalert2.min.css') }}" rel="stylesheet">
    <script src="{{ asset('assets/plugins/sweet-alert/sweetalert2.all.min.js') }}"></script>

    <script>

        let teacherAvailability;
        $(function () {

            $('#timetableCalendar').fullCalendar({
                header: {
                    left: '',
                    center: '',
                    right: ''
                },
                plugins: ['momentPlugin', 'formatDate'],
                // height: 680, // Fix height
                columnFormat: 'dddd', // Display just full length of weekday, without dates
                defaultView: 'agendaWeek', // display week view
                // hiddenDays: [0,6], // hide Saturday and Sunday
                weekNumbers: false, // don't show week numbers
                minTime: '06:00:00', // display from 16 to
                maxTime: '20:00:00', // 23
                slotDuration: '00:15:00', // 15 minutes for each row
                allDaySlot: false, // don't show "all day" at the top
                aspectRatio: 1.5,
                editable: true,
                selectable: true,
                selectHelper: true,
                droppable: true, // this allows things to be dropped onto the calendar
                /*select: function (start, end, allDay) {
                    // Code for creating new events.
                },*/
                eventResize: function (event, delta, revertFunc, jsEvent, ui, view) {
                    // Code when you resize an event (for example make it two hours longer
                    eventActions(event);
                },
                eventDrop: function (event, jsEvent, ui, view) {
                    // Code when you drop an element somewhere else
                    eventActions(event);
                },
                eventRender: function (event, element, view) {
                    element.innerHTML = event.title;
                },
                eventClick: function(event, jsEvent, view) {
                    getEventDetails(event.id);
                },
                timeZone: 'UTC',
                /*events: {
                    url: '{{ route('timetable.calender_events') }}',
                    type: 'GET',
                    data: {
                        class_id: $("#_ref_class_id").val(),
                        division_id: $("#_ref_section_id").val()
                    },
                    error: function () {
                        alert('there was an error while fetching events!');
                    }
                }*/
                backgroundColor: '#1880c9'
            });

        });

        function eventActions(event) {
            let startTime = (moment(event.start._d)).subtract({hours: 5, minutes: 30}).format('HH:mm:ss');
            let endTime = (moment(event.end._d)).subtract({hours: 5, minutes: 30}).format('HH:mm:ss');
            let startDate = (moment(event.start._d)).subtract({hours: 5, minutes: 30});
            let dow = startDate.day();
            let _ref = event.id;

            let url = "{{ route('timetable.update', 'timetableRef') }}";
            url = url.replace('timetableRef', _ref);
            let data = {start_time: startTime, end_time: endTime, dow: dow, teacher_id: event.teacher_id};
            __callTimetableAction(url, 'PATCH', data, 'event');
            // reRenderEvent();
        }

        async function getEventDetails(eventId) {
            let url = "{{ route('timetable.edit', 'eventId') }}";
            url = url.replace('eventId', eventId);
            let data = await __getTimetableDetails(url, 'GET');
        }

        function reRenderEvent() {
            let classId = $("#_ref_class_id").val();
            let sectionId = $("#section_id").val();
            if(!inputValidation(classId) || !inputValidation(sectionId)){
                return false;
            }

            let events = {
                url: '{{ route('timetable.calender_events') }}',
                type: 'GET',
                data: {
                    class_id: classId,
                    division_id: sectionId
                },
                error: function () {
                    alert('there was an error while fetching events!');
                },
            };
            $('#timetableCalendar').fullCalendar('removeEventSource', events);
            $('#timetableCalendar').fullCalendar('addEventSource', events);
            // $('#timetableCalendar').fullCalendar('refetchEvents');
        }

        $(document).on('change', '.__sms__change__section', function () {
            reRenderEvent();
        });
        $(document).on('change', '.__change__student__class', function () {
            reRenderEvent();
        });


        $(function () {
            teacherAvailability = $('#{{ $moduleName.'-table-availability'}}').DataTable({
                serverSide: false,
                autoWidth: false,
                responsive: false,
                orderClasses: false,
                paging: false,
                searching: false,
                bInfo: false,
                ajax: {
                    url: "{{ route($moduleName.'.teacher_availability') }}",
                    data: function (d) {
                        d.teacher_id = $("#_ref_teacher_id").val();
                        d.week_day = $("#_ref_week_day").val();
                    },
                },
                columns: [
                    {data: 'class', name: 'class'},
                    {data: 'time', name: 'time'},
                ],
                columnDefs: [
                    {className: "__sms__ta__right", targets: "_all"},
                ],
                order: [[0, 'desc']],
            });

            $('.__sms__check__availability').on('change', function (e) {
                let _ref_teacher_id = $("#_ref_teacher_id").val();
                let _ref_week_day = $("#_ref_week_day").val();
                if(!inputValidation(_ref_teacher_id) || !inputValidation(_ref_week_day)){
                    return false;
                }
                teacherAvailability.ajax.reload();
            });

            $("#_ref_teacher_id, #_ref_week_day").change(function () {
                teacherAvailability.ajax.reload();
            });

        });

    </script>

    <script>
        let actionUrl = {
            '_success_msg': "{{__('locale.timetable_saved')}}"
        };

        $(document).ready(function () {
            $(".__sms__change__time").change(function () {
                let startTime = $("#_ref_start_time").val();
                let endTime = $("#_ref_end_time").val();

                if(startTime != '' && startTime!=null && endTime!='' && endTime!=null){

                    let start = new Date('1970-01-01 ' + startTime);
                    let end = new Date('1970-01-01 ' + endTime);
                    let diff = end.getTime() - start.getTime(); // this is a time in milliseconds
                    let diffAsDate = new Date(diff);

                    $("#_ref_total_time").val(diffAsDate.getUTCHours() + ":" + diffAsDate.getUTCMinutes());
                }
            });
        });
    </script>
@stop

