<style>
    #All .marginul {
        margin-left: 10px;
    }
    .activetype{
        background: #eee !important;
    }
    .activedate{
        background: #eee !important;
    }
    a.fa.fa-calendar.display.marginul {
        margin-left: 10px;
    }
    .text-line-through{
        text-decoration:line-through !important;
    }
    .text-white{
        color: white;
    }
    a{
        color: #4c0870;
    }

</style>
<link href='<?php echo THEME_PATH; ?>plugins/fullcalendar-4.2.0/packages/core/main.css' rel='stylesheet' />
<link href='<?php echo THEME_PATH; ?>plugins/fullcalendar-4.2.0/packages/daygrid/main.css' rel='stylesheet' />
<link href='<?php echo THEME_PATH; ?>plugins/fullcalendar-4.2.0/packages/timegrid/main.css' rel='stylesheet' />
<link href='<?php echo THEME_PATH; ?>plugins/fullcalendar-4.2.0/packages/list/main.css' rel='stylesheet' />
<script src='<?php echo THEME_PATH; ?>plugins/fullcalendar-4.2.0/packages/core/main.js'></script>
<script src='<?php echo THEME_PATH; ?>plugins/fullcalendar-4.2.0/packages/interaction/main.js'></script>
<script src='<?php echo THEME_PATH; ?>plugins/fullcalendar-4.2.0/packages/daygrid/main.js'></script>
<script src='<?php echo THEME_PATH; ?>plugins/fullcalendar-4.2.0/packages/timegrid/main.js'></script>
<script src='<?php echo THEME_PATH; ?>plugins/fullcalendar-4.2.0/packages/list/main.js'></script>
<div class="container-fluid container-fixed-lg bg-white">
    <div class="panel panel-transparent">
        <div class="panel-body">
            <div class="row">
                <div class="col-md-2">
                    <a style="color:white !important;" class="btn bg-complete-dark" id="add_activity" data-toggle="modal" data-target="#activity_modal" data-origin="calendar">
                        <?php print CommonLanguage::getMessage('add_activity'); ?>
                    </a> 
                </div>
                <div class="col-md-1s pull-right hidden">
                    <div id="demo" class='pull-right' style="border-radius: 4px; background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc; width: 200%">
                        <i class="glyphicon glyphicon-calendar fa fa-calendar"></i>&nbsp;
                        <span>choose a custom date</span> 
                        <b class="pull-right"><i class='fa fa-arrow-down'></i></b>
                    </div>
                </div>
            </div>
            <div class="row" id="filter">
                <span id="type">
                    <ul class="pagination">
                        <li><a class="activetype type" id="Alltype" data-value = "0"><?php  echo CommonLanguage::getMessage('all');?> </a></li>
                        <li><a class="type" data-value = "1"><?php  echo CommonLanguage::getMessage('call');?>  </a></li>
                        <li><a class="type" data-value = "2"><?php  echo CommonLanguage::getMessage('meeting');?>  </a></li>
                        <li><a class="type" data-value = "3"><?php  echo CommonLanguage::getMessage('dead_line');?>   </a></li>
                        <li><a class="type" data-value = "4"><?php  echo CommonLanguage::getMessage('task');?>  </a></li>
                        <li>
                            <a class="fa fa-calendar display marginul " data-show="#calendarhandler" data-hide="#tablehandler" data-placement="bottom" title="Calendar" ></a>
                        </li>
                        <li>
                            <a class=" fa fa-table activetype display " data-hide="#calendarhandler" data-show="#tablehandler"  data-placement="bottom" title="Table" ></a>
                        </li>
                        <li id="All"><a class="activedate date marginul"> <?php  echo CommonLanguage::getMessage('all');?></a></li>
                        <li id="planned" ><a class="date"><?php  echo CommonLanguage::getMessage('planned');?></a></li>
                        <li id="overdue" ><a class="date"><?php  echo CommonLanguage::getMessage('overdue');?></a></li>
                        <li><a class="date filter_type_btn" data-date-id='1'><?php  echo CommonLanguage::getMessage('today');?></a></li>
                        <li ><a class="date filter_type_btn" data-date-id='2'><?php  echo CommonLanguage::getMessage('tomorrow');?></a></li>
                        <li ><a class="date filter_type_btn" data-date-id='3'><?php  echo CommonLanguage::getMessage('this_week');?></a></li>
                        <li ><a class="date filter_type_btn"  data-date-id='4'><?php  echo CommonLanguage::getMessage('next_week');?></a></li>
                        <li ><a class="date filter_type_btn"  data-date-id='5'><?php  echo CommonLanguage::getMessage('this_month');?></a></li>
                    </ul>
                </span>
            </div>
            <div class="row form-group">
                <div class="col-md-3">
                    <label for="type"><?php print CommonLanguage::getMessage('Action'); ?></label>
                    <select name="action_type_id" id="action_type_id" class="full-width" data-init-plugin="select2">
                        <option value=""><?php  echo CommonLanguage::getMessage('select');?></option>
                        <option value="1"><?php  echo CommonLanguage::getMessage('reorder');?></option>
                        <option value="2"><?php  echo CommonLanguage::getMessage('no_need');?></option>
                        <option value="3"><?php  echo CommonLanguage::getMessage('call_again');?></option>
                    </select>
                </div> 
                <div class="col-md-2">
                    <label for="type"><?php print CommonLanguage::getMessage('status'); ?></label>
                    <select name="status_id" id="status_id" class="full-width" data-init-plugin="select2">
                        <option value=""><?php  echo CommonLanguage::getMessage('select');?></option>
                        <option value="1"><?php  echo CommonLanguage::getMessage('done');?></option>
                        <option value="0" selected><?php  echo CommonLanguage::getMessage('not_done');?></option>
                    </select>
                </div>
            </div>
            <div class="row" id="calendarhandler">
                <div id="calendar1"></div>
            </div>
            <div class="row m-t-10" id="tablehandler">
                <table class="table table-bordered demo-table-search crm-table" id="tableWithSearch">
                    <thead>
                        <tr>
                            <th class="text-center" style="width:5%;"><?php print CommonLanguage::getMessage('done'); ?></th>
                            <th class="text-center"><?php print CommonLanguage::getMessage('customer'); ?></th>
                            <th class="text-center"><?php print CommonLanguage::getMessage('deal'); ?></th>
                            <th class="text-center" style="width:8%;"><?php print CommonLanguage::getMessage('type'); ?></th>
                            <th class="text-center" ><?php print CommonLanguage::getMessage('notes'); ?></th>
                            <th class="text-center"  style="width:10%;"><?php print CommonLanguage::getMessage('added_date'); ?></th>
                            <th class="text-center"  style="width:10%;"><?php print CommonLanguage::getMessage('due_duration'); ?></th>
                            <th class="text-center"  style="width:10%;"><?php print CommonLanguage::getMessage('action_type'); ?></th>
                            <th class="text-center"><?php print CommonLanguage::getMessage('Action'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
            </div>
        </div>
        <?php echo Forms::ModalLoader('calendar_loader'); ?>
    </div>
</div>
<script>
    var activity_list = <?php echo json_encode(CommonLanguage::getMessage('activity_list'));?>,
        typeoffilter = 0,current_date = null,clickedEventOnCalendar,calendar,
            calendarEl = document.getElementById('calendar1');
    $(function(){ 
        RebuildDataTable(activity_list,[0,1,2,3,4,5,6,7],'crmAjax/activityList',{activity_type_id:typeoffilter,current_date:current_date,action_type_id:$('#action_type_id').val(),status_id:$('#status_id').val()});
        $('#action_type_id,#status_id').on('change',function(){
            RebuildDataTable(activity_list,[0,1,2,3,4,5,6,7],'crmAjax/activityList',{activity_type_id:typeoffilter,current_date:current_date,action_type_id:$('#action_type_id').val(),status_id:$('#status_id').val()});
            renderCalendarEvent();
        });
        $("#calendarhandler").hide()
        $('#demo').daterangepicker({
            "showDropdowns": true,
            "showWeekNumbers": true,
            "timePicker24Hour": true,
            "timePickerSeconds": true,
            "autoApply": true,
            /*
			ranges: {
				'Today': [moment(), moment()],
				'Tomorrow': [moment().add(1, 'days'), moment().add(1, 'days')],
				'This week': [moment(), moment().add(6, 'days')],
				'next week': [moment().add(6, 'days'), moment().add(12, 'days')],
				'This Month': [moment().startOf('month'), moment().endOf('month')],
				'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
			},*/
            "locale": {
                "format": "YYYY-MM-DD",
                "separator": " -> ",
                "applyLabel": "Apply",
                "cancelLabel": "Cancel",
                "fromLabel": "From",
                "toLabel": "To",
                //	"customRangeLabel": "Custom",
                "weekLabel": "W",
                "daysOfWeek": [
                    "Su",
                    "Mo",
                    "Tu",
                    "We",
                    "Th",
                    "Fr",
                    "Sa"
                ],
                "monthNames": [
                    "January",
                    "February",
                    "March",
                    "April",
                    "May",
                    "June",
                    "July",
                    "August",
                    "September",
                    "October",
                    "November",
                    "December"
                ],
                "firstDay": 1
            },
        });
        $("#demo").on("apply.daterangepicker", function(ev, picker) {
            $('#calendar1').fullCalendar('changeView', 'agenda');
            $('#calendar1').fullCalendar('option', 'visibleRange', {
                start: picker.startDate.format('YYYY-MM-DD'),
                end: picker.endDate.format('YYYY-MM-DD')
            });
            activity.date = picker.startDate.format('YYYY-MM-DD') + "->" + picker.endDate.format('YYYY-MM-DD');
            $("#demo span").html(activity.date);
        })
        $("#tableWithSearch").on("click", "input[name=check_done]", function () {
            var check = $("input[name=check_done][data-id="+$(this).attr("data-id")+"]:checked").length > 0 ? 1 : 0;
            $.ajax({
                url: "crmAjax/updateActivityStatus",
                type: "POST",
                data: {activity_id: $(this).attr("data-id"),activity_checked: check},
                dataType: "JSON",
                complete: function (jqXHR, status) {
                    if (status == 'success') {
                        if (jqXHR.responseJSON[1] == "success") {
                            RebuildDataTable(activity_list,[0,1,2,3,4,5,6,7],'crmAjax/activityList',{activity_type_id:typeoffilter,current_date:current_date,action_type_id:$('#action_type_id').val(),status_id:$('#status_id').val()})
                        }
                    }
                }
            });
        });
        $("#filter").on("click", "a.type", function (event) {
            event.preventDefault();
            //clear any clicked type
            clearactivetype();
            //make the clicked button active
            $(this).addClass("activetype");
            //trim text
            typeoffilter = $(this).attr('data-value');
            if ($("#calendarhandler").css("display") != "none") {
                $('#type li a.filter_type_btn').addClass('hidden');
                renderCalendarEvent();
            }else{
                $('#type li a.filter_type_btn').removeClass('hidden');
                RebuildDataTable(activity_list,[0,1,2,3,4,5,6,7],'crmAjax/activityList',{activity_type_id:typeoffilter,current_date:current_date,action_type_id:$('#action_type_id').val(),status_id:$('#status_id').val()})
            }
        });
        $("#filter").on("click", "a.date", function (event) {
            $("#demo span").html('choose a custom date');
            var getdatetext = $(this).text().toLowerCase().trim();
            event.preventDefault();
            //clear active date
            clearactivedate();
            //make it active
            $(this).addClass("activedate");
            //assign value that we will send via ajax
            if (getdatetext == "all")
                current_date = "";
            else if (getdatetext.toLocaleLowerCase() == "planned" || getdatetext.toLocaleLowerCase() == "overdue")
                current_date = getdatetext;
            else {
                console.log($(this).attr('data-date-id'));
                switch ($(this).attr('data-date-id')) {
                    case '1':
                        current_date = moment().format('YYYY-MM-DD') + "->" + moment().format('YYYY-MM-DD');
                        break;
                    case '2':
                        current_date = moment().add(1, 'days').format('YYYY-MM-DD') + "->" + moment().add(1, 'days').format('YYYY-MM-DD');
                        break;
                    case '3':
                        console.log(moment().format('YYYY-MM-DD'))
                        console.log(moment().add(6, 'days').format('YYYY-MM-DD'))
                        current_date = moment().format('YYYY-MM-DD') + "->"+ moment().add(6, 'days').format('YYYY-MM-DD');
                        break;
                    case '4':
                        current_date = moment().add(6, 'days').format('YYYY-MM-DD') + "->" + moment().add(12, 'days').format('YYYY-MM-DD');
                        break;
                    case '5':
                        current_date = moment().startOf('month').format('YYYY-MM-DD')+"->"+moment().endOf('month').format('YYYY-MM-DD');
                        break;
                                                    }
            }
            //fill table
            if ($("#calendarhandler").css("display") != "none") {
                renderCalendarEvent();
                $('#type li a.filter_type_btn').addClass('hidden');
                //check if calendar is displayed  same as top
            }else{
                RebuildDataTable(activity_list,[0,1,2,3,4,5,6,7],'crmAjax/activityList',{activity_type_id:typeoffilter,current_date:current_date,action_type_id:$('#action_type_id').val(),status_id:$('#status_id').val()})
                $('#type li a.filter_type_btn').removeClass('hidden');
            }
        });
        calendar = new FullCalendar.Calendar(calendarEl, {
            plugins: [ 'interaction', 'dayGrid', 'timeGrid', 'list' ],
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'dayGridMonth,timeGridWeek,timeGridDay,listMonth'
            },
            formatDate:'YYYY-mm-dd',
            selectHelper: true,
            editable: true,
            minTime: "06:00:00",
            maxTime: "24:00:00",
            height: 500,
            droppable: true, 
            navLinks: true, // can click day/week names to navigate views
            businessHours: true, // display business hours
            eventLimit: true, // allow "more" link when too many events
            events: "crmAjax/getAllActivities?type="+typeoffilter+"&status_id="+$('#status_id').val()+"&current_date="+current_date,
            eventResize: function (info) {
                var activity_id = info.event.id,
                    start_date = moment(info.event.start).format("YYYY-MM-DD HH:mm:ss"),
                    end_date = moment(info.event.end).format("YYYY-MM-DD HH:mm:ss");
                updateCalendarDetails(activity_id, start_date, end_date);
            },
            eventDrop: function (info) {
                var activity_id = info.event.id,
                    start_date = moment(info.event.start).format("YYYY-MM-DD HH:mm:ss"),
                    end_date = moment(info.event.end).format("YYYY-MM-DD HH:mm:ss");
                updateCalendarDetails(activity_id, start_date, end_date);
            },
            eventClick: function(info) {
                $('#activity_modal').modal('show');
                activity_origin = 'calendar';
                edit_activity_trigger(info.event.id)
            }
        });
        calendar.render();
    });
    function renderCalendarEvent(){
        var eventSources = calendar.getEventSources(); 
        var len = eventSources.length;
        for (var i = 0; i < len; i++) { 
            eventSources[i].remove(); 
        } 
        calendar.addEventSource("crmAjax/getAllActivities?type="+typeoffilter+"&status_id="+$('#status_id').val()+"&current_date="+current_date);
    }
    function updateCalendarDetails(id,start,end){
        $('#calendar_loader').removeClass('hidden');
        $.ajax({
            type: "POST",
            url: "crmAjax/UpdateActivityTime",
            data: {activity_id:id,start_date:start,end_date:end},
            dataType: "JSON",
            complete: function (jqXHR, status) {
                if (status == 'success') {
                    if (jqXHR.responseJSON[1] == "success") {
                        toastr.success(jqXHR.responseJSON[0]);
                        renderCalendarEvent();
                        RebuildDataTable(activity_list,[0,1,2,3,4,5,6,7],'crmAjax/activityList',{activity_type_id:typeoffilter,current_date:current_date,action_type_id:$('#action_type_id').val(),status_id:$('#status_id').val()})

                    }else{
                        toastr.error(jqXHR.responseJSON[0]);
                    }
                }
                $('#calendar_loader').addClass('hidden');
            }
        });
    }
    $(document).on("click", "a.display", function () {
        console.log('display')
         //save element we want to save
        var clickeditem = $(this).attr("data-show");
        //save element we want to hide
        var hideitem = $(this).attr("data-hide");
        //clear date filter data if exist
        current_date = null;
        typeoffilter = "";
        $("#demo span").html('choose a custom date');
        //always show date filter in case of table hide it later if its calendar
        $("#date li").show();
        //toggle and display the layout we want
        toggle($(clickeditem), $(hideitem));
        //clear all the labels and filter if they are active
        clearactivedate();
        clearactivetype();
        cleardisplay();
        $("#All a").addClass("activedate");
        $("#Alltype").addClass("activetype");
        //make it active the button we click calendar or table
        $(this).addClass("activetype");
        //refill table as default value no filter
        //			table.ajax.reload(null, false);
        //        //check if the layoput  is calendar
        if ($("#calendarhandler").css("display") != "none") {
            renderCalendarEvent();
            $('#type li a.filter_type_btn').addClass('hidden');
        }else{
            RebuildDataTable(activity_list,[0,1,2,3,4,5,6,7],'crmAjax/activityList',{activity_type_id:typeoffilter,current_date:current_date,action_type_id:$('#action_type_id').val(),status_id:$('#status_id').val()})
            $('#type li a.filter_type_btn').removeClass('hidden');
        }
    });
    function toggle(selector_main, selector_secondary, cb) {
        //show new display
        selector_main.show();
        //hide old one
        selector_secondary.hide();
        if (cb != null)
            cb();
    }
    //clear active type element
    function clearactivetype () {
        $("#filter a.type").each(function () {
            $(this).removeClass("activetype");
        });
    }
    //clear active date element
    function clearactivedate  () {
        $("#filter a.date").each(function () {
            $(this).removeClass("activedate");
        });
    }
    //clear active display element
    function cleardisplay() {
        $("#filter a.display").each(function () {
            $(this).removeClass("activetype");
        });
    }
</script>
<?php include 'Views/crm/activity_modal.php';?>
