@extends('backend._partials.app')
@section('maincontent')
    <style type="text/css">
        .selectedEvent{
            background-color: #CCD9DC;
        }
        #userList tr{
            cursor: pointer;
        }
    </style>

    <div class="col-md-7">
        <div class="card">
            <div class="header text-center">
            </div>
            <div class="content" id="loadCalendar">
                <div id="fullCalendar"></div>
            </div>
        </div>
    </div>
    <div class="col-md-5">
        <div class="card">
            <div class="header text-center">
                <h4 class="title text-info">Event Management</h4>
                <small>You can manage all event including weekend</small>

            </div>
            <div class="content">
                {!! Form::open(['url'=>'saveEvent','id'=>'myForm']) !!}
                <div class="form-group">
                    <label class="control-label">Select User Group <star>*</star></label>
                    {!! Form::select('user_group_id',$userGroup,null,['class'=>'form-control','id'=>'userGroup','required'=>'true']) !!}
                </div>
                <div>
                    <div class="form-group">
                        <label class="control-label">Event Title <star>*</star></label>
                        <input class="form-control" name="event_title" type="text" required="true"  placeholder="Start typing here.."/>
                    </div>
                    <div class="form-group">
                        <label class="control-label">Event Type <star>*</star></label>
                        {!! Form::select('event_type',$eventType,null,['class'=>'form-control','required'=>'true','id'=>'eventType']) !!}
                    </div>
                    <div id="officeStatus">

                    </div>

                    <div class="form-group">
                        <label class="control-label">Event Details <star>*</star></label>
                        <textarea rows="3" name="details" class="form-control" id="eventDetails" placeholder="Event Details"></textarea>
                    </div>
                    <div class="form-group">
                        <div class="panel-group" id="accordion">
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <h4 class="panel-title">
                                        <a data-target="#groupMembers" href="javascript:void(0)" data-toggle="collapse" class="collapsed" aria-expanded="false">
                                            Group Members<small>[ Click here for see the group members]</small>
                                            <b class="caret"></b>
                                        </a>
                                    </h4>
                                </div>
                                <div id="groupMembers" class="panel-collapse collapse" aria-expanded="false" style="height: 0px;">
                                    <div class="panel-body">
                                        <table  class="table table-striped table-bordered table-hover" cellspacing="0" width="100%" style="width:100%">
                                            <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>User Name</th>
                                                <th>Email</th>
                                            </tr>
                                            </thead>
                                            <tbody id="userList">
                                            @foreach($users as $user)
                                                <tr>
                                                    <td><input type="checkbox" class="user_id" checked name="user_id" value="{{$user['id']}}"></td>
                                                    <td>{{$user['name']}}</td>
                                                    <td>{{$user['email']}}</td>
                                                </tr>
                                                @endforeach
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>


                        </div>
                    </div>
                    <div class="form-group">
                    <button type="submit" class="btn btn-info btn-fill pull-right" id="submit">SUBMIT</button>
                    </div>

                    <div class="clearfix"></div>

                    {!! Form::close() !!}




                </div>
            </div>
        </div>
    </div>

    <script>

        $(document).ready(function () {
            var userGroupId={{$defaultGroup}};
            @if(Session::get('currentMonth'))
                today = new Date('{{Session::get('currentMonth')}}');
            @else
                today = new Date();
            @endif
                var yearMonth= today.getFullYear()+"-"+((today.getMonth()+1)<10? '0'+(today.getMonth()+1) : (today.getMonth()+1)); //year and month
                getEvent(userGroupId,yearMonth);
                getUserList(userGroupId);
                /* user group wise calender load*/
            $("#userGroup").change(function () {
                userGroupId= $(this).val();
                getEvent(userGroupId,yearMonth);
                getUserList(userGroupId);


            });
            $("#eventType").change(function () {
                var eventTypeId= $(this).val();
                $.ajax({
                    url: "{{URL::to('selectEventType')}}/"+eventTypeId,
                    method: 'GET',
                    dataType: 'json',
                    success: function(data) {
                        $("#officeStatus").empty();
                        if(data.error=='true'){
                            $("#officeStatus").html("<span class='text-danger'>Please select Event Type</span>");
                            return;
                        }
                        if(data.office_status==1){
                            var isCheckedOpen='checked';
                        }else{
                            var isCheckedClose='checked';
                        }
                        $("#officeStatus").append('<div class="form-group">'+
                            '<label class="control-label">Office Status</label>'+
                            '<input type="radio" name="office_status" id="open" value="1"'+ isCheckedOpen +'><label for="open">Open</label> &nbsp;'+
                            '<input type="radio" name="office_status" value="0" id="close"'+ isCheckedClose +'><label for="close">Close</label>'+
                            '</div>');
                    },
                    error: function () {
                        alert("Something wrong. please refresh!");
                    }
                });


            });





            /* Retrieve data based on usergroup and year month when click next/prev button*/
            $('.fc-prev-button').click(function(){
                var date = $('#fullCalendar').fullCalendar('getDate')._d;
                yearMonth= date.getFullYear()+"-"+((date.getMonth()+1)<10? '0'+(date.getMonth()+1) : (date.getMonth()+1)); //year and month
                getEvent(userGroupId,yearMonth);
            });

            $('.fc-next-button').click(function(){
                var date = $('#fullCalendar').fullCalendar('getDate')._d;
                yearMonth= date.getFullYear()+"-"+((date.getMonth()+1)<10? '0'+(date.getMonth()+1) : (date.getMonth()+1)); //year and month
                getEvent(userGroupId,yearMonth);
            });

        });
        $(document).on('click',"#userList td",function(e){
            var chk = $(this).closest("tr").find("input:checkbox").get(0);
            if(e.target != chk)
            {
                chk.checked = !chk.checked;
            }
        });


        function getUserList(userGroupId) {
            $.ajax({
                url: "{{URL::to('getMembersByUserGroup')}}/"+userGroupId,
                method: 'GET',
                dataType: 'json',
                success: function(data) {
                    $("#userList").empty();
                    for(var i=0; i<data.length; i++){
                        $("#userList").append("<tr>" +
                            '<td><input type="checkbox" class="user_id" checked name="user_id" value='+ data[i].id +'></td>'+
                            "<td>" +data[i].name+"</td>"+
                            "<td>" +data[i].email+"</td>"+
                            "</tr>");
                    }
                }
            });
        }
        var selectedEventDate=[];
        function getEvent(userGroupId,date){
            var events = [];
            var eventCreatedStatus = '';
            $.ajax({
                url: "{{URL::to('getEvent')}}/"+userGroupId+"/"+date,
                async: false,
                dataType: 'json',
                success: function (data) {
                    events = data;
                }
            });

            $calendar = $('#fullCalendar');
            y = today.getFullYear();
            m = today.getMonth();
            d = today.getDate();

            $calendar.fullCalendar({
                header: {
                    left: 'title',
                    right: 'prev,next today'
                },
                defaultDate: today,
                selectable: true,
                selectHelper: false,
                titleFormat: {
                    month: 'MMMM YYYY', // September 2015
                    week: "MMMM D YYYY", // September 2015
                    day: 'D MMM, YYYY'  // Tuesday, Sep 8, 2015
                },
                select: function (start, end) {
                },
                dayClick: function (start, jsEvent, view) {
                    var event_date = new Date(start);
                    y = event_date.getFullYear();
                    m= parseInt(event_date.getMonth())+1;
                    m= (m<10)? '0'+m: m;
                    d = (event_date.getDate() < 10) ? '0' + event_date.getDate() : event_date.getDate();
                    event_date = y + "-" + m + "-" + d;

                    if($(this).hasClass('selectedEvent')){
                        $(this).removeClass('selectedEvent');
                        selectedEventDate.splice(selectedEventDate.indexOf(event_date), 1);
                    }else{
                        $(this).addClass('selectedEvent');
                        selectedEventDate.push(event_date);
                    }
                    //selectedEventDate=Array.from(new Set(selectedEventDate)); //reset the array index

                },
                eventLimit: true, // allow "more" link when too many events
                events: events,
                eventClick: function(calEvent, jsEvent, view) {
                    var e=this;

                    swal({
                            title: 'Are you want to delete?',
                            html: '<p><b>Event Title:</b> '+calEvent.title +'</p>',
                            showCancelButton: true,
                            closeOnConfirm: true,
                            closeOnCancel: true,
                        },
                        function (isConfirm) {
                            if (isConfirm) {
                                $.ajax({
                                    url: "{{URL::to('deleteEvent')}}/"+calEvent.client_event_detail_id,
                                    type: 'GET',
                                    dataType: 'json',
                                    success:function (data) {
                                        if(data.success){
                                            $(e).hide();
                                        }else{
                                            errorNotify(data.error);
                                        }
                                    }
                                });
                            }
                        })
                }

            });
            $('#fullCalendar').fullCalendar( 'removeEvents');
            $('#fullCalendar').fullCalendar( 'addEventSource', events);


        }

        $("#myForm").validate({
            submitHandler: function() {
                $.ajax({
                    url: $('#myForm').attr('action'),
                    method: 'POST',
                    data: {
                        '_token':'{{csrf_token()}}',
                        'selectedDate':selectedEventDate,
                        'user_group_id':$("select[name='user_group_id']").val(),
                        'event_type':$("select[name='event_type']").val(),
                        'office_status':$('input[name=office_status]:checked').val(),
                        'event_title':$("input[name='event_title']").val(),
                        'details':$("textarea[name='details']").val(),
                        'user_list':$('.user_id:checked').serialize(),
                    },
                    dataType: 'json',
                    success: function(data) {
                        if(data.error){
                            errorNotify(data.error);
                        }else if(data.success){
                            window.location.href="{{URL::to('event')}}";
                        }
                    },
                    error: function (data) {
                        swal("Something wrong. please refresh the page!")
                    }
                });
            }
        });

    </script>
@endsection