<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../lib/auth.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

requireLogin();

$pageTitle = 'Planning Calendar';
$siteName  = 'Crop Monitor';
$userId    = getCurrentUserId();

include __DIR__ . '/../layouts/header.php';
include __DIR__ . '/../layouts/navbar.php';
?>

<div id="layoutSidenav">
<div id="layoutSidenav_nav"><?php include __DIR__ . '/../layouts/sidebar.php'; ?></div>
<div id="layoutSidenav_content"><main><div class="container-fluid px-4">
<h1 class="mt-4"><?= htmlspecialchars($pageTitle, ENT_QUOTES, 'UTF-8') ?></h1>
<ol class="breadcrumb mb-4">
    <li class="breadcrumb-item"><a href="/dashboard/dashboard.php">Dashboard</a></li>
    <li class="breadcrumb-item active">Planning Calendar</li>
</ol>

<!-- custom scripts --> 
<script type="text/javascript" src='client-assets/fullcalendar/js/moment.min.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/locale/en-au.js"></script>

<!-- fullcalendar  -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.10.0/fullcalendar.css" />
    <!-- <link rel="stylesheet" href="client-assets/fullcalendar/css/fullcalendar.print.css" media='print' /> -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.print.css" integrity="sha256-eODYvezY8MWH5O2DbXi3BwOJESNqpDfU1rmBLT72PyQ=" crossorigin="anonymous" media='print' />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.10.0/fullcalendar.js"></script>

<!-- scheduler -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar-scheduler/1.9.4/scheduler.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar-scheduler/1.9.4/scheduler.js"></script>

<script type="text/javascript" src="https://use.fontawesome.com/1e2844bb90.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous" />

<!-- Include Bootstrap Datepicker -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.css" integrity="sha256-b5ZKCi55IX+24Jqn638cP/q3Nb2nlx+MH/vMMqrId6k=" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js" integrity="sha256-5YmaxAwMjIpMrVlK84Y/+NjCpKnFYa8bWWBbUHSBGfU=" crossorigin="anonymous"></script>

<!-- Bootstrap Date-Picker Plugin -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css"/>

<style>
    .fc-view table {
        margin-bottom: 0px;
    }
    .fc-content {
    	/* color: white !important; */
    }
    .fc-head-container {
    	background-color: #D82508;
    	color: white;
    	border: 1px solid #D82508 !important;
    }
</style>	

<div class="container-fluid">
	<div class="row">
		<div class="col">
			<div id="calendar"></div>
		</div>
	</div>
</div>



<!--  Modal  to Add Event -->
<div class="modal" id="createEventModal" tabindex="-1" role="dialog" aria-hidden="true" >
  <div class="modal-dialog" role="document">
    <!--  Modal content-->
    <div class="modal-content">
      <div id="modalHeader" class="modal-header">
		<h4 class="modal-title">Add Event to Schedule</h4>
		<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
	  </div>
      <div class="modal-body">
        <div class="control-group">
          <label class="control-label" for="inputPatient">Event:</label>
          <div class="field desc">
            <input class="form-control" id="title" name="title" placeholder="Event" type="text" value="">
            <input type="hidden" id="modx_user_id" value="<?= (int) $userId ?>">
          </div>
        </div>
        
        <hr>
        
        <div class="row">
			<div class="col">
				<label class="control-label" for="startTime">Start Time:</label>
				<input class="form-control startTime" type="text" id="startTime" >
			</div>
			<div class="col">
				<label class="control-label" for="endTime">End Time:</label>
				<input class="form-control endTime" type="text" id="endTime" >
			</div>
		</div>
		
		<script type="text/javascript">
			$(function () {
				$('.startTime').datetimepicker();
				$('.endTime').datetimepicker({
					//format: 'L',
					format: 'yyyy-mm-dd hh:ii',
					daysOfWeekDisabled: [0, 6],
					collapse: true,
					useCurrent: false //Important! See issue #1075
				});
				$(".startTime").on("dp.change", function (e) {
					$('.endTime').data("DateTimePicker").minDate(e.date);
				});
				$(".endTime").on("dp.change", function (e) {
					$('.startTime').data("DateTimePicker").maxDate(e.date);
				});
			});
		</script>
		
		</div>
        <div id="modalFooter" class="modal-footer">
            <button type="button" class="btn btn-secondary" data–dismiss="createEventModal" aria–hidden="true">Close</button>
            <button type="submit" class="btn btn-success" id="submitButton" aria–hidden="true">Save</button>
        </div>
			  
        <!--
        <div class="control-group">
          <label class="control-label" for="when">When:</label>
          <div class="controls controls-row" id="when" style="margin-top:5px;"> </div>
        </div>
        -->
      </div>
      
    </div>
  </div>
</div>

<!--  Modal to Event Details -->
<div class="modal" id="calendarModal" tabindex="-1" role="dialog" aria-hidden="true" >
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div id="modalHeader" class="modal-header">
            <h4 class="modal-title">Event Details</h4>
		    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
      
        <div id="modalBody" class="modal-body">
            
            <!-- <div id="modalWhen" style="margin-top:5px;"></div> -->
            
            <div class="row">
    			<div class="col" >
    			    <h4 id="modalTitle" class="modal-title"></h4>
                </div>
    		</div>
    		
    		<hr>
            <div class="row">
    			<div class="col" >
    				<label for="eventID">From:</label>
    				<input type="text" class="form-control form-control-sm datetimepicker" id="startTime" readonly>
    			</div>
    		</div>
    		<div class="row">
    			<div class="col" >
    				<label for="eventID">To:</label>
    				<input type="text" class="form-control form-control-sm datetimepicker" id="endTime" readonly>
    			</div>
    		</div>
    		
    		<!--
    		<hr>
    		<div class="row">
    			<div class="col" >
    		        <div id="modalWhen" style="margin-top:5px;"></div>
                </div>
    		</div>
    		-->
    		
    		<script type="text/javascript">
    			$(document).ready(function(){
    				$('.datetimepicker').datetimepicker({
    					format: 'dddd, MMMM Do YYYY, h:mm',
    					showTodayButton: true,
    					useCurrent: true,
    					stepping: 60,
    					daysOfWeekDisabled: [0, 6],
    					collapse: true,
    					useCurrent: false //Important! See issue #1075
    				});
    			});
    		</script>
		</div>
		<input type="hidden" id="eventID"/>
		
        <div class="modal-footer">
    		<button type="button" class="btn btn-secondary" data–dismiss="modal" aria–hidden="true">Cancel</button>
    		<button type="submit" class="btn btn-success" id="updateButton" aria–hidden="true">Update</button>
    		<button type="submit" class="btn btn-danger" id="deleteButton">Delete</button>
    	</div>
	
	</div>
  </div>
</div>
<!-- Modal-->





<script type="text/javascript">
    
    $(document).ready(function(){
    var calendar = $('#calendar').fullCalendar({  // assign calendar
        plugins: [ 'bootstrap4', 'interaction', 'list' ],
		themeSystem: 'bootstrap4',
		timeZone: 'UTC',
		defaultView: 'month',
		aspectRatio: 2,

		allDayDefault: true,
		stick: true,

		header: {
			left: 'today  prev,next',
			center: 'title ',
			right: 'timeGridThreeMonths, month, listWeek, listMonth' //agendaWeek, agendaDay,
		},

		droppable: true, // this allows things to be dropped onto the calendar
		eventLimit: true, // when too many events in a day, show the popover

		displayEventTime: false, //https://fullcalendar.io/docs/displayEventTime
		
		editable: true, // enable draggable events
		eventStartEditable: true,
		eventResizableFromStart: true,
		eventDurationEditable: true,
		
		resizable: true,
		
		selectable: true,
        allDaySlot: false,
		contentHeight: 'auto',
		
		weekNumbers: true,
		weekNumbersWithinDays: true,
		
		views: {
			timeGridFourDays: {
			  type: 'timeline',
			  duration: { days: 5 },
			  buttonText: '4 days'
			},
			timeGridFourWeeks: {
				type: 'timeline',
				duration: { days: 28 },
				buttonText: '4 Weeks'
			},
			timeGridThreeMonths: {
				buttonText: '3 Months',
				type: 'timeline',
				duration: { days: 95 },
				buttonText: '3 Months'
			},
			month: {
				buttonText: 'Month',
				titleFormat: '#M. MMMM YYYY'
				//allDay: true
			},
			agendaWeek: {
				allDaySlot: true,
				nowIndicator: true
			},
			agendaDay: {
				minTime: '05:00:00',
				maxTime: '19:00:00',
				nowIndicator: true
			},
			listDay: { 
				buttonText: 'List Day'
			},
			listWeek: { buttonText: 'List Week' },
			listMonth: { buttonText: 'List Month' }
		},

		resourceLabelText: 'Current Jobs',
		schedulerLicenseKey: 'CC-Attribution-NonCommercial-NoDerivatives',

        //resources: 'https://fullcalendar.io/demo-resources.json?with-nesting&with-colors',
        
        //events: 'https://fullcalendar.io/demo-events.json?single-day&for-resource-timeline'
        //events: "index.php?view=1",  // request to load current events
        
        //events: '[[!calendar_index? &view=1]]',
        eventSources: [
            'ci.html?view=1',
            'http://api.openweathermap.org/data/2.5/forecast?lat=-41.179&lon=147.545&cnt=10&mode=json&units=metric&appid=a164361b43628b08cfa06c0a9fd03a02', //needs formatting to show min-max temps for each day
        ],
        
        eventTextColor: '#fff !important',
        
        eventRender: function(event, element) {
            // PLANT IS GREEN
			if(event.type == 'plant' || event.type == 'Dry Ash Test') {
				element.css({
					'background-color': '#008000',  
					'border-color': '#008000'
				});
            }
			// SOIL IS BROWN
			else if(event.type == 'soil' || event.type == 'Soil Test') {
				element.css({
					'background-color': '#a52a2a',  
					'border-color': '#a52a2a'
				});
            }
			// WATER IS BLUE
			else if(event.type == 'water') {
				element.css({
					'background-color': '#0000FF',
					'border-color': '#0000FF',
				});				
            }
			// ANIMAL IS ORANGE
			else if(event.type == 'animal') {
				element.css({
					'background-color': '#FFA500',				
					'border-color': '#FFA500'
				});				
            }
			// WEATHER IS BLACK
			else if(event.type == 'weather') {
				element.css({
					'background-color': '#ffffff',
					'border-color': '#ffffff',
					'color': '#212529 !important',
					'font-weight': 'bold',
					'text-align': 'center'
				});				
            }
			// REST IS SILVER
			else {
				element.css({
					'background-color': '#C0C0C0',
					'border-color': '#C0C0C0'
				});
			}
        },
            
            
        eventClick:  function(event, jsEvent, view) {  // when some one click on any event
            endtime = $.fullCalendar.moment(event.end).format('dddd, MMMM Do YYYY, h:mm');
            starttime = $.fullCalendar.moment(event.start).format('dddd, MMMM Do YYYY, h:mm');
            var mywhen = starttime + ' – ' + endtime;
            $('#calendarModal #modx_user_id').html(modx_user_id);
            $('#calendarModal #modalTitle').html(event.title);
            $('#calendarModal #modalWhen').text(mywhen);
            $('#calendarModal #eventID').val(event.id);
            $('#calendarModal #startTime').val(starttime);
            $('#calendarModal #endTime').val(endtime);
            $('#calendarModal').modal();
        },
                
        select: function(start, end, jsEvent) {  // click on empty time slot
            endtime = $.fullCalendar.moment(end).format('dddd, MMMM Do YYYY, h:mm');
            starttime = $.fullCalendar.moment(start).format('dddd, MMMM Do YYYY, h:mm');
            var mywhen = starttime + ' – ' + endtime;
            start = moment(start).format('YYYY-MM-DD hh:mm');
            end = moment(end).format('YYYY-MM-DD hh:mm');
            $('#createEventModal #startTime').val(start);
            $('#createEventModal #endTime').val(end);
            $('#createEventModal #when').text(mywhen);
            $('#createEventModal').modal('toggle');
        },
       
        eventDrop: function(event, delta){ // event drag and drop
           $.ajax({
               //url: 'index.php',
               url: '/api/calendar.php',
               data: 'action=update&title='+event.title+'&start='+moment(event.start).format()+'&end='+moment(event.end).format()+'&id='+event.id+'&modx_user_id='+modx_user_id ,
               type: "POST",
               success: function(json) {
                   //alert(json);
               }
           });
        },
       
        eventResize: function(event) {  // resize to increase or decrease time of event
           $.ajax({
               //url: 'index.php',
               url: '/api/calendar.php',
               data: 'action=update&title='+event.title+'&start='+moment(event.start).format()+'&end='+moment(event.end).format()+'&id='+event.id+'&modx_user_id='+modx_user_id,
               type: "POST",
               success: function(json) {
                   //alert(json);
               }
           });
        }
    
    });



    $('#deleteButton').on('click', function(e){ // delete event clicked
       // We don't want this to act as a link so cancel the link action
       e.preventDefault();
       doDelete(); // send data to delete function
    });
    
    
    function doDelete(){  // delete event 
       $("#calendarModal").modal('hide');
       var eventID = $('#eventID').val();
       var modx_user_id = $('#modx_user_id').val();
       $.ajax({
           //url: 'index.php',
           url: '/api/calendar.php',
           data: 'action=delete&id='+eventID+'&modx_user_id='+modx_user_id,
           type: "POST",
           success: function(json) {
               if(json == 1)
                    $("#calendar").fullCalendar('removeEvents',eventID);
               else
                    return false;
           }
       });
    }
    
    
    $('#submitButton').on('click', function(e){ // add event submit
       // We don't want this to act as a link so cancel the link action
       e.preventDefault();
       doSubmit(); // send to form submit function
    });
    
    function doSubmit(){ // add event
       $("#createEventModal").modal('hide');
       var title = $('#title').val();
       var modx_user_id = $('#modx_user_id').val();
       var startTime = $('#startTime').val();
       var endTime = $('#endTime').val();
       
       $.ajax({
           //url: 'index.php',
           url: '/api/calendar.php',
           data: 'action=add&title='+title+'&start='+startTime+'&end='+endTime+'&modx_user_id='+modx_user_id,
           type: "POST",
           success: function(json) {
               $("#calendar").fullCalendar('renderEvent',
               {
                   id: json.id,
                   title: title,
                   start: startTime,
                   end: endTime,
               },
               true);
           }
       });
       
    } 
    
    $('#updateButton').on('click', function(e){ // delete event clicked
           // We don't want this to act as a link so cancel the link action
           e.preventDefault();
           doUpdate(); //send data to delete function
       });
    
    function doUpdate(){  // delete event 
       $("#calendarModal").modal('hide');
	   var startTime = 	$('#calendarModal #startTime').val();
       var endTime = 	$('#calendarModal #endTime').val();
	   var quote = 		$('#calendarModal #quote').val();
	   var eventType = 	$('#calendarModal #eventType').val();
	   var eventID = 	$('#calendarModal #eventID').val();
	   var quid = 		$('#calendarModal #quid').val();
       $.ajax({
           //url: 'index.php',
           url: '/api/calendar.php',
           data: 'action=project_update&id='+eventID+'&quote='+quote+'&title='+title+'&start='+startTime+'&end='+endTime+'&eventType='+eventType+'&quid='+quid,
           type: "POST",
           success: function(json) {
               $("#calendar").fullCalendar('renderEvent',
               {
                   id: eventID,
				   quote: quote,
                   title: quote,
                   start: startTime,
                   end: endTime,
				   type: eventType,
				   quid: quid,
               },
               true);
           }
       });
   }
   
   
    function fetchWeatherForecast(location, $http, $filter){
        $http.get("http://api.openweathermap.org/data/2.5/forecast?lat=-41.179&lon=147.545&cnt=10&mode=json&units=metric&appid=a164361b43628b08cfa06c0a9fd03a02").success(function(data) {
            addWeatherToCalendar(data, $filter);
        });
    }
    function addWeatherToButton(weatherData, $filter){
        var date = new Date();
        for (var i = 0; i < weatherData.list.length; i++) {
            var element = angular.element('td.fc-day[data-date="' + $filter('date')(date, 'yyyy-MM-dd').toString() + '"]')
            var html = element[0].innerHTML
            var icon = weatherData.list[i].weather[0].icon
            var temp = weatherData.list[i].temp.max + "-" +weatherData.list[i].temp.min
            element.append("<span><img src='http://openweathermap.org/img/w/"+icon+".png'/>"+temp+"</span>")
            date.setDate(date.getDate() + 1);
        }
    }
    


});
</script>
</div></main>
<?php include __DIR__ . '/../layouts/footer.php'; ?>
</div></div>
