@extends('layouts.app')
@section('title', 'Event List')
@section('content')

    <link rel="stylesheet" href="{{asset('assets/fullcalendar/lib/main.min.css')}}">
   
    <style>
        :root {
            --bs-success-rgb: 71, 222, 152 !important;
        }

        html,
        body {
            height: 100%;
            width: 100%;
        }

        .btn-info.text-light:hover,
        .btn-info.text-light:focus {
            background: #000;
        }

        table,
        tbody,
        td,
        tfoot,
        th,
        thead,
        tr {
            border-color: #ededed !important;
            border-style: solid;
            border-width: 1px !important;
        }

    </style>

<section class="content">
      <div class="row">  
<div class="col-12">
  <div class="box">

   <div class="box-body">   
    <h4 class="box-title text-info mb-0"><i class="fa fa-list"></i> Calender</h4>
          <hr class="my-15"> 

    <div class="container py-5" id="page-container">
        <div class="row">
            <div class="col-md-9">
                <div id="cal"></div>
            </div>
            <div class="col-md-3">
                <div class="card rounded-0 shadow">
                <div class="card-header bg-gradient bg-primary ">
                        <div class="card-title">Event Form</div>
                    </div>
                    <div class="card-body">
                        <div class="container-fluid"style="padding-left:0px;padding-right:0px;">
                            <form action="{{ route('save.schedule') }}" method="post" id="schedule-form">
                                @csrf
                                <input type="hidden" name="id" value="">
                                <div class="form-group mb-2">
                                    <label for="title" class="control-label">Title</label>
                                    <input type="text" class="form-control" name="title" id="title" required>

                                </div>
                                <div class="form-group mb-2">
                                    <label for="description" class="control-label">Description</label>
                                    <textarea rows="3" class="form-control" name="description" id="description" required></textarea>
                                </div>
                                <div class="form-group mb-2">
                                    <label for="start_date" class="control-label">Start Date</label>
                                    <!-- <input type="date" class="form-control form-control-sm rounded-0" name="start_date" id="start_date" required> -->
                                    <input type="date" id="start_date" name="start_date" min="<?php echo date('Y-m-d'); ?>"class="form-control"required>
                                </div>
                                <div class="form-group mb-2">
                                <label for="start_time" class="control-label">Start Time</label>
                                <select class="form-select" name="start_time" id="start_time" required>
                                    <option value="">Select Time</option>
                                    <!-- Generate options for 15-minute intervals -->
                                    @for ($i = 0; $i < 24 * 4; $i++)
                                        @php
                                            $hours = floor($i / 4);
                                            $minutes = ($i % 4) * 15;
                                            $time = sprintf('%02d:%02d', $hours, $minutes);
                                        @endphp
                                        <option value="{{ $time }}">{{ $time }}</option>
                                    @endfor
                                </select>
                            </div>

                                <div class="form-group mb-2">
                                    <label for="end_date" class="control-label">End Date</label>
                                    <input type="date" class="form-control" min="<?php echo date('Y-m-d'); ?>"name="end_date" id="end_date" required>
                                </div>
                                <div class="form-group mb-2">
                                <label for="end_time" class="control-label">End Time</label>
                                <select class="form-select " name="end_time" id="end_time" required>
                                    <option value="">Select Time</option>
                                    <!-- Generate options for 15-minute intervals -->
                                    @for ($i = 0; $i < 24 * 4; $i++)
                                        @php
                                            $hours = floor($i / 4);
                                            $minutes = ($i % 4) * 15;
                                            $time = sprintf('%02d:%02d', $hours, $minutes);
                                        @endphp
                                        <option value="{{ $time }}">{{ $time }}</option>
                                    @endfor
                                </select>
                            </div>
                  
                            </div>
                            <div style="text-align:center;">
                                <button class="btn btn-primary" type="submit"><i class="fa fa-save"></i> Save</button>
                                <button class="btn btn-default" type="reset"><i class="fa fa-reset"></i> Cancel</button>
                        </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Event Details Modal -->
    <div class="modal fade" tabindex="-1" data-bs-backdrop="static" id="event-details-modal">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content rounded-0">
                <div class="modal-header rounded-0">
                    <h5 class="modal-title">Schedule Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body rounded-0">
                    <div class="container-fluid">
                        <dl>
                            <dt class="text-muted">Title</dt>
                            <dd id="modal-title" class="fw-bold fs-4"></dd>
                            <dt class="text-muted">Description</dt>
                            <dd id="modal-description"></dd>
                            <dt class="text-muted">Start</dt>
                            <dd id="modal-start"></dd>
                            <dt class="text-muted">End</dt>
                            <dd id="modal-end"></dd>
                        </dl>
                    </div>
                </div>
                <div class="modal-footer rounded-0">
                    <div class="text-end">
                        <button type="button" class="btn btn-primary btn-sm rounded-0" id="edit" data-id="">Edit</button>
                        <button type="button" class="btn btn-danger btn-sm rounded-0" id="delete" data-id="">Delete</button>
                        <button type="button" class="btn btn-secondary btn-sm rounded-0" data-bs-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    </div>
			    </div>
			  </div> 
			</div>
		</section>
    <!-- Event Details Modal -->
    <script src="{{asset('assets/fullcalendar/lib/main.min.js')}}"></script>
    
    <script src="{{asset('assets/fullcalendar/lib/moment.min.js')}}"></script>

<script>
$('#start_date, #start_time').on('change', function() {
    // Get start date and time values
    var startDate = $('#start_date').val();
    var startTime = $('#start_time').val();

    // Get end date and time values
    var endDate = $('#end_date').val();
    var endTime = $('#end_time').val();

    // Convert date and time strings to Date objects for comparison
    var startDateTime = new Date(startDate + 'T' + startTime);
    var endDateTime = new Date(endDate + 'T' + endTime);

    // Compare start and end dates/times
    if (startDateTime >= endDateTime) {
        // Display error message or handle validation as needed
        toastr.error('Start date/time cannot be greater than or equal to end date/time.');
        // Clear the start date and time fields (optional)
        $('#start_date').val('');
        $('#start_time').val('');
    }
});
        // Add event listener for end date and end time change
        $('#end_date, #end_time').on('change', function() {
            // Get start date and time values
            var startDate = $('#start_date').val();
            var startTime = $('#start_time').val();

            // Get end date and time values
            var endDate = $('#end_date').val();
            var endTime = $('#end_time').val();

            // Convert date and time strings to Date objects for comparison
            var startDateTime = new Date(startDate + 'T' + startTime);
            var endDateTime = new Date(endDate + 'T' + endTime);

            // Compare start and end dates/times
            if (startDateTime >= endDateTime) {
                // Display error message or handle validation as needed
                toastr.error('End date/time cannot be less than or equal to start date/time.');
                // Clear the end date and time fields (optional)
                $('#end_date').val('');
                $('#end_time').val('');
            }
        });
      var calendar;
    var Calendar = FullCalendar.Calendar;
    var events = [];
    var scheds = {!! json_encode($sched_res) !!};

    $(function() {

        if (!!scheds) {
            Object.keys(scheds).map(k => {
                var row = scheds[k]
                events.push({ id: row.id, title: row.title, start: row.start, end: row.end});
            })
        }
        
        var date = new Date()
        var d = date.getDate(),
        m = date.getMonth(),
        y = date.getFullYear()
        
        calendar = new Calendar(document.getElementById('cal'), {
            headerToolbar: {
                left: 'prev,next today',
                right: 'dayGridMonth,dayGridWeek,list',
                center: 'title',
            },
            selectable: true,
            themeSystem: 'bootstrap',
            //Random default events
            events: events,
            eventClick: function(info) {
    var _details = $('#event-details-modal')
    var id = parseInt(info.event.id); // Convert ID to integer
    // console.log("Clicked Event ID:", id);

    // Check if ID is a valid number
    if (!isNaN(id)) {
        // console.log("Data Type of ID:", typeof id); // Check data type of ID

        var clickedEvent = scheds.find(event => event.id === id);
        var startDate = new Date(clickedEvent.start);
        var currentDate = new Date();
   // Convert both start date and current date to date objects without time
var startDateOnly = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate());
var currentDateOnly = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate());

if (startDateOnly < currentDateOnly) {
    // Disable the Edit button for past events
    _details.find('#edit').prop('disabled', true);
} else {
    // Enable the Edit button for current date events and future events
    _details.find('#edit').prop('disabled', false);
}


        if (clickedEvent) {
            // console.log("Clicked Event Data:", clickedEvent);
            // Use the clickedEvent object here
            _details.find('#modal-title').text(clickedEvent.title);
        _details.find('#modal-description').text(clickedEvent.description);
        _details.find('#modal-start').text(moment(clickedEvent.start).format('MMMM DD, YYYY hh:mm A'));
_details.find('#modal-end').text(moment(clickedEvent.end).format('MMMM DD, YYYY hh:mm A'));


            _details.find('#edit,#delete').attr('data-id', id);
            _details.modal('show');
        } else {
            alert("Event with ID " + id + " is not found.");
        }
    } else {
        alert("Invalid event ID.");
    }
},
            eventDidMount: function(info) {
                // Do Something after events mounted
            },
            editable: true
        });

        calendar.render();

        // Form reset listener
        $('#schedule-form').on('reset', function() {
            $(this).find('input:hidden').val('')
            $(this).find('input:visible').first().focus()
        })

// Edit Button
$(document).on('click', '#edit', function() {
    var id = parseInt($(this).attr('data-id')); // Parse the ID as an integer
    console.log('Clicked ID:', id); // Debugging
    console.log('All Events:', scheds); // Debugging
    if (scheds.length > 0) {
        var clickedEvent = scheds.find(event => event.id === id); // Find the event by ID
        console.log(clickedEvent);
        if (clickedEvent) {
            console.log('Clicked Event Data:', clickedEvent); // Debugging
            var _form = $('#schedule-form');
            _form.find('[name="id"]').val(id);
            _form.find('[name="title"]').val(clickedEvent.title);
            _form.find('[name="description"]').val(clickedEvent.description);
            // Separate date and time from clickedEvent.start
const startDate = clickedEvent.start.substring(0, 10); // Extracts the date part (YYYY-MM-DD)
const startTime = clickedEvent.start.substring(11, 16); // Extracts the time part (HH:MM)

// Separate date and time from clickedEvent.end
const endDate = clickedEvent.end.substring(0, 10); // Extracts the date part (YYYY-MM-DD)
const endTime = clickedEvent.end.substring(11, 16); // Extracts the time part (HH:MM)

// Set the values in separate input fields
_form.find('[name="start_date"]').val(startDate);
_form.find('[name="start_time"]').val(startTime);
_form.find('[name="end_date"]').val(endDate);
_form.find('[name="end_time"]').val(endTime);
            // _form.find('[name="start_datetime"]').val(String(clickedEvent.start).replace(" ", "T"));
            // _form.find('[name="end_datetime"]').val(String(clickedEvent.end).replace(" ", "T"));
            _form.find('[name="timezone"]').val(clickedEvent.timezone);

            $('#event-details-modal').modal('hide');
            _form.find('[name="title"]').focus();
        } else {
            alert("Event not found");
        }
    } else {
        alert("No events available");
    }
});



$(document).on('click', '#delete', function() {
    var id = parseInt($(this).attr('data-id')); // Parse the ID as an integer
    console.log('Clicked ID:', id); // Debugging
    console.log('All Events:', scheds); // Debugging
    if (scheds.length > 0) {
        var clickedEvent = scheds.find(event => event.id === id); // Find the event by ID
        console.log('Clicked Events:', clickedEvent); // Debugging

        if (clickedEvent) {
            var _conf = confirm("Are you sure to delete this scheduled event?");
            if (_conf === true) {
                // Construct the delete URL dynamically based on your application's routing
                var deleteUrl = "/delete-schedule/" + id; // Construct URL with the event ID
                // Redirect to the delete URL
                window.location.href = deleteUrl;
            }
        } else {
            alert("Event not found");
        }
    } else {
        alert("No events available");
    }
});


    })
    </script>

@endsection
