@extends('backend.layouts.app')

@section('style')
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.css" />

    <style>
        .fc-event .fc-title {
            text-align: center;
            display: block;
        }
        

        .fc-event {
            display: flex;
            align-items: center;
            justify-content: center;
            white-space: normal;
        }
    </style>

@endsection

@section('title', @$data['title'])

@section('content')
    {!! breadcrumb([
        'title' => @$data['title'],
        route('admin.dashboard') => _trans('common.Dashboard'),
        route('user.index') => _trans('common.Employees'),
        '#' => @$data['title'],
    ]) !!}

    <div class="table-content table-basic">
        <div class="card">
            <div class="card-body d-flex flex-column gap-5">
                <div class="row bg-light p-3 shadow-sm align-items-center">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label class="mb-3" for="name">{{ _trans('common.Employees') }}
                                <span class="text-danger">*</span>
                            </label>
                            <select id="employee_id" class="form-control select2 w-100" onchange="searchDutyCalendar()">
                                <option value="" disabled selected>{{ _trans('common.Choose One') }}</option>
                                @foreach ($data['employees'] ?? [] as $employee)
                                    <option value="{{ $employee->id }}" {{ old('employee_id') == $employee->id ? "selected" : '' }}>
                                        {{ $employee->name }}
                                        @if ($employee->employee_id)
                                            - {{ $employee->employee_id }}
                                        @endif
                                        @if($employee->lastDutyCalendar)
                                            - {{ \Carbon\Carbon::parse($employee->lastDutyCalendar->date)->format('M-Y') }}
                                        @endif
                                    </option>
                                @endforeach
                            </select>
                        </div>
                        @if (hasPermission('duty_calendar_create'))
                            <button id="btn_generate" class="btn btn-gradian mt-3">{{ _trans('common.Generate') }}</button>
                        @endif
                    </div>
                </div>

                {{-- Show calendar view --}}
                <div>
                    <div id='duty_calendar'></div>
                </div>
            </div>
        </div>
    </div>

    @include("specialattendance::dutySchedule.add_modal")

    @include("specialattendance::dutySchedule.edit_modal")
@endsection

@section('script')
<script src="{{ global_asset('modules/SpecialAttendance/assets/js/app.js') }}"></script>

<!-- Include FullCalendar and its plugins -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.js"></script>

<script>
    let isEditPermission = `{{ hasPermission('duty_calendar_update') }}`;

    let calendarInitialized = false;
    let initialRender = true;

    // Add duty calendar
    $('#btn_generate').click(function() {
        $('#addDutyCalendarModal').modal('show');
        syncEmployeeSelection();
    });

    $(document).ready(function() {
        // Show the modal when it has validation errors
        @if ($errors->any())
            $('#addDutyCalendarModal').modal('show');
        @endif

        // Update event
        $('#duty_calendar_update_form').on('submit', function(event) {
            event.preventDefault();

            var formData = $(this).serialize();

            $.ajax({
                url: $(this).attr('action'),
                type: 'POST',
                data: formData,
                success: function(response) {
                    $('#editDutyCalendarModal').modal('hide');

                    // Get the current view
                    let currentView = $('#duty_calendar').fullCalendar('getView');
                    let month       = currentView.title.split(' ')[0];
                    let year        = currentView.start.clone().format('YYYY');

                    if (month === 'January' && currentView.start.month() === 11) {
                        year = currentView.start.clone().add(1, 'years').format('YYYY');
                    }

                    fetchDutyCalendar($("#employee_id").val(), month, year);
                },
                error: function() {
                    alert('There was an error while updating the event.');
                }
            });
        });
    });

    // Hide employee section when select department
    function selectDepartment() {
        let departmentId = $('select[name="department_id"]').val();
        if (departmentId) {
            $('#employee_section').addClass('d-none');
        } else {
            $('#employee_section').removeClass('d-none');
        }
    }

    function syncEmployeeSelection() {
        var selectedEmployeeId = $('#employee_id').val();
        $('#add_duty_calendar_form').find('.text-danger').hide();

        $('#addDutyCalendarModal').find('select[name="employee_id"]').val(selectedEmployeeId).trigger('change');
    }

    function searchDutyCalendar() {
        let employeeId = $("#employee_id").val();

        if (!calendarInitialized) {
            initDutyCalendar();
        }

        let currentView = $('#duty_calendar').fullCalendar('getView');
        
        // Extract month and year from the title directly
        let title = currentView.title;  // "January 2025"
        let month = title.split(' ')[0]; // "January"
        let year = title.split(' ')[1];  // "2025"

        if (employeeId) {
            fetchDutyCalendar(employeeId, month, year);
        }
    }

    function initDutyCalendar() {
        if (!calendarInitialized) {
            $('#duty_calendar').fullCalendar({
                editable: false,
                selectable: true,
                dayClick: function(date, jsEvent, view) {
                    console.log("day");
                },
                eventClick: function(event) {
                    if (!isEditPermission) {
                        Toast.fire({
                            icon: 'warning',
                            title: `{{ _trans('common.You do not have permission to edit!') }}`,
                            timer: 1500,
                        });

                        return false;
                    }

                    if (event.leave_id || !event.is_editable) {
                        return false;
                    }

                    $('#editDutyCalendarModal').modal('show');
                    $('#weekendCheckboxContainer').addClass('d-none');
                    $('#holidayCheckboxContainer').addClass('d-none');
                    $('#makeWeekend').addClass('d-none');

                    $('#duty_calendar_id').val(event.id);
                    $('#duty_schedule_id').val(event.duty_schedule_id).trigger('change');

                    if (event.duty_schedule_id) {
                        $('#makeWeekend').removeClass('d-none');
                    } else {
                        $('#make_weekend').prop('checked', false);
                    }

                    if (event.is_weekend == 1) {
                        $('#weekendCheckboxContainer').removeClass('d-none');
                        $('#isWeekend').prop('checked', true);
                        $('#isWeekend').val(event.is_weekend);
                        $('#is_weekend').val(1);
                    } else {
                        $('#isWeekend').prop('checked', false);
                        $('#is_weekend').val(0);
                    }

                    if (event.holiday_id) {
   
                        $('#holidayCheckboxContainer').removeClass('d-none');
                        $('#isHoliday').prop('checked', true);
                        $('#holiday_label').text(event.holiday_title);
                        $('#holiday_id').val(event.holiday_id);

                        $('#makeWeekend').addClass('d-none');
                        $('#make_weekend').prop('checked', false);
                    } else {
                        $('#isHoliday').prop('checked', false);
                        $('#holiday_id').val('');
                    }
                },
                viewRender: function(view, element) {
                    let employeeId = $("#employee_id").val();
                    let month      = view.title.split(' ')[0];
                    let year       = view.start.clone().format('YYYY');

                    if (month === 'January' && view.start.month() === 11) {
                        year = view.start.clone().add(1, 'years').format('YYYY');
                    }

                    if (initialRender) {
                        initialRender = false;
                        return;
                    }

                    if (employeeId && month && year) {
                        fetchDutyCalendar(employeeId, month, year);
                    }
                },
            });

            calendarInitialized = true;
        }
    }

    function fetchDutyCalendar(employeeId, month, year) {
        initDutyCalendar();

        let calendar = $('#duty_calendar').fullCalendar();

        calendar.fullCalendar('removeEvents');

        $.ajax({
            url: `{{ route('duty.calendar.event') }}`,
            type: 'GET',
            data: {
                employee_id: employeeId,
                month      : month,
                year       : year
            },
            success: function(data) {
                console.log(data);
                calendar.fullCalendar('renderEvents', data);
            },
            error: function() {
                alert('There was an error while fetching events.');
            }
        });
    }
</script>

@endsection
