@extends('layouts.adminmaster')

@section('styles')

    <!-- INTERNAL Data table css -->
    <link href="{{asset('build/assets/plugins/datatable/css/dataTables.bootstrap5.min.css')}}?v=<?php echo time(); ?>" rel="stylesheet" />
    <link href="{{asset('build/assets/plugins/datatable/responsive.bootstrap5.css')}}?v=<?php echo time(); ?>" rel="stylesheet" />

    <!-- INTERNAL Sweet-Alert css -->
    <link href="{{asset('build/assets/plugins/sweet-alert/sweetalert.css')}}?v=<?php echo time(); ?>" rel="stylesheet" />

    <!-- INTERNAL Datepicker css-->
    <link href="{{asset('build/assets/plugins/modal-datepicker/datepicker.css')}}?v=<?php echo time(); ?>" rel="stylesheet" />

    <!-- INTERNAL Sweet-Alert css -->
    <link href="{{asset('build/assets/plugins/sweet-alert/sweetalert.css')}}?v=<?php echo time(); ?>" rel="stylesheet" />

    <!-- INTERNAl color css -->
    <link rel="stylesheet" href="{{asset('build/assets/plugins/colorpickr/themes/nano.min.css')}}?v=<?php echo time(); ?>">

    <style>
        #hideAfterloading {
            position: absolute;
            top: 100px;
            left: 45%;
        }

        /* spell check and suggestion */
        #holidaydescription {
            position: relative;
            border: 1px solid #ccc;
            padding: 10px;
            min-height: 40px;
            width: 100%;
            font-size: 16px;
            /* height: 100% !important; */
        }

        #suggestionText {
            padding: 4px 8px;
            font-size: 14px;
            color: #333;
            pointer-events: none;
            opacity: 0.5;
            z-index: 999;
            white-space: nowrap;
        }

        .misspelled {
            text-decoration: underline wavy red;
            cursor: pointer;
            position: relative;
        }

        .correctedtooltip {
            padding: 5px 10px;
            border-radius: 5px;
            color: #333;
            font-size: 12px;
            white-space: nowrap;
            z-index: 100000;
            cursor: pointer;
        }

        .editable-container {
            position: relative;
            width: 100%;
            height: auto;
        }

        .editable-container::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            padding: 8px;
            color: #aaa;
            pointer-events: none;
            user-select: none;
            transition: opacity 0.2s ease;
        }

        .editable-container div[contenteditable]:empty::before {
            content: 'Enter Holiday Description';
            opacity: 0.3;
        }

        .editable-container div[contenteditable]:not(:empty)::before {
            content: '';
        }

        .editable-container div[contenteditable] {
            padding: 8px;
            box-sizing: border-box;
        }
    </style>

@endsection

@section('content')

{{-- page header start --}}
<div class="page-header d-xl-flex d-block">
    <div class="page-leftheader">
        <div class="page-title"><span class="font-weight-normal text-muted ms-2">{{lang('Holiday Announcement')}}</span></div>
    </div>
</div>
{{-- page header start --}}

{{-- card start --}}
<div class="card">
    <div class="card-header  border-0">
        <h4 class="card-title">{{lang('Holidays Lists')}}</h4>
        <div class="card-options mt-sm-max-2 d-md-max-block">
            @can('Holidays Create')

            <a href="#" class="btn btn-success mb-md-max-2 me-3 text-capitalize" id="addholidaymodal"><i class="feather feather-user-plus"></i> {{lang('add holiday')}}</a>
            @endcan
            @can('Holidays Import Access')
            <a href="{{route('holidays.import')}}" class="btn btn-info mb-md-max-2 me-3"><i class="feather feather-download"></i> {{lang('Import Holidays List')}}</a>
            @endcan
        </div>
    </div>

    <div class="card-body" style="min-height: 250px;">
        <div class="table-responsive spruko-delete">
            @can('Holidays Delete')

            <button id="massdeletenotify" class="btn btn-outline-light btn-sm mb-4 data-table-btn" style="display: none;"><i class="fe fe-trash"></i> {{lang('Delete')}}</button>
            @endcan

            <table class="table table-bordered border-bottom text-nowrap ticketdeleterow w-100" id="support-articlelists">
                <thead>
                    <tr>
                        <th  width="10">{{lang('Sl.No')}}</th>
                        @can('Holidays Delete')

                            <th width="10" >
                                <input type="checkbox"  id="customCheckAll" class="form-check-input">
                                <label  for="customCheckAll"></label>
                            </th>
                        @endcan
                        @cannot('Holidays Delete')

                            <th width="10" >
                                <input type="checkbox"  id="customCheckAll" class="form-check-input" disabled>
                                <label  for="customCheckAll"></label>
                            </th>
                        @endcannot

                        <th >{{lang('ocassion')}}</th>
                        <th >{{lang('Day')}}</th>
                        <th >{{lang('Date')}}</th>
                        <th >{{lang('Status')}}</th>
                        <th >{{lang('Actions')}}</th>
                    </tr>
                </thead>
                <div id="hideAfterloading"><img src="{{ asset('build/assets/images/loader.svg') }}" alt="">
                    <p>{{lang('loading.. Please Wait')}}</p>
                </div>
            </table>
        </div>
    </div>
</div>
{{-- card end --}}

@endsection
@section('modal')
    @include('admin.holidays.modal')

@endsection

@section('scripts')
    <!-- INTERNAL Data tables -->
    <script src="{{asset('build/assets/plugins/datatable/js/jquery.dataTables.min.js')}}?v=<?php echo time(); ?>"></script>
    <script src="{{asset('build/assets/plugins/datatable/js/dataTables.bootstrap5.js')}}?v=<?php echo time(); ?>"></script>
    <script src="{{asset('build/assets/plugins/datatable/dataTables.responsive.min.js')}}?v=<?php echo time(); ?>"></script>
    <script src="{{asset('build/assets/plugins/datatable/responsive.bootstrap5.min.js')}}?v=<?php echo time(); ?>"></script>
    <script src="{{asset('build/assets/plugins/datatable/datatablebutton.min.js')}}?v=<?php echo time(); ?>"></script>
    <script src="{{asset('build/assets/plugins/datatable/buttonbootstrap.min.js')}}?v=<?php echo time(); ?>"></script>

    <!-- INTERNAL Sweet-Alert js-->
    <script src="{{asset('build/assets/plugins/sweet-alert/sweetalert.min.js')}}?v=<?php echo time(); ?>"></script>

    <script src="{{asset('build/assets/plugins/jquery/jquery-ui.js')}}?v=<?php echo time(); ?>"></script>

    <!-- INTERNAL color pickr -->
    <script src="{{ asset('build/assets/plugins/colorpickr/pickr.min.js') }}?v=<?php echo time(); ?>"></script>

    <script src="{{ asset('build/assets/plugins/typomaster/typojs.min.js') }}"></script>

    <script type="text/javascript">
        "use strict";

        document.addEventListener("DOMContentLoaded", (event) => {

            let tableData = @json($holidays);

            let dateFormat = @json(setting('date_format'));
            let delPerm = @json(Auth::user()->can('Holidays Delete'));
            let editPerm = @json(Auth::user()->can('Holidays Edit'));

            var dataTable;
            var tableDropDown;

            loadTable(tableData);

            function truncateTitle(title) {
                const maxLength = 40;
                return title.length > maxLength ? title.substring(0, maxLength) + '...' : title;
            }

            function formatdayname(createdtime){
                const holidayStartDate = new Date(createdtime);
                const options = { weekday: 'long' };
                const dayName = holidayStartDate.toLocaleString('en-US', options);
                return dayName;
            }

            function formatdmy(createdtime){
                const holidayStartDate = new Date(createdtime);
                const day = String(holidayStartDate.getDate()).padStart(2, '0');
                const month = String(holidayStartDate.getMonth() + 1).padStart(2, '0');
                const year = holidayStartDate.getFullYear();
                const formattedDate = `${day}-${month}-${year}`;
                return formattedDate;
            }

            function loadTable(tableData) {
                document.getElementById('hideAfterloading')?.classList.remove('d-none');
                document.getElementById('theadShow')?.classList.add('d-none');
                if (tableDropDown)
                    tableDropDown.destroy();

                if (dataTable)
                    dataTable.destroy();

                if (document.getElementById('tableBody'))
                    document.getElementById('tableBody').remove();

                let createTbody = document.createElement('tbody');
                createTbody.setAttribute('id', "tableBody");
                let rows = tableData.map((data, index) => {

                    return `
                        <tr>
                            <td class="sorting_1">${index + 1}</td>

                            <td class="sorting_1">
                                ${delPerm ? `<input type="checkbox" name="spruko_checkbox[]" class="checkall form-check-input" value="${data.id}" />` : '~'}
                            </td>

                            <td class="font-weight-semibold">${data.occasion}</td>

                            <td>
                                ${data.enddate == data.startdate ? formatdayname(data.startdate) : formatdayname(data.startdate)+"--"+formatdayname(data.enddate)}
                            </td>

                            <td>
                                ${formatdmy(data.startdate)} ${data.enddate ? ' -- '+formatdmy(data.enddate) : ''}
                            </td>

                            <td>
                                ${editPerm ?
                                    (data.status == '1' ?
                                    `<label class="custom-switch form-switch mb-0">
                                        <input type="checkbox" name="status" data-id="${data.id}" id="myonoffswitch${data.id}" value="1" class="custom-switch-input tswitch" checked>
                                        <span class="custom-switch-indicator"></span>
                                    </label>`
                                    :
                                    `<label class="custom-switch form-switch mb-0">
                                        <input type="checkbox" name="status" data-id="${data.id}" id="myonoffswitch${data.id}" value="1" class="custom-switch-input tswitch" >
                                        <span class="custom-switch-indicator"></span>
                                    </label>`
                                    )
                                    :
                                    ''
                                }
                            </td>

                            <td>
                                <div class = "d-flex">
                                    ${editPerm ? `<a href="javascript:void(0);" class="action-btns1" id="editholidaymodal" data-id="${data.id}" data-bs-toggle="tooltip" data-bs-placement="top" title="{{lang('Edit')}}"><i class="feather feather-edit text-primary"></i></a>` : ''}

                                    ${delPerm ? `<a href="javascript:void(0);" class="action-btns1 deleteholiday" id="deleteholidaymodal" data-id="${data.id}" data-bs-toggle="tooltip" data-bs-placement="top" title="{{lang('Delete')}}"><i class="feather feather-trash-2 text-danger"></i></a>` : ''}
                                </div>

                            </td>

                        </tr>
                    `;
                });

                if (tableData.length == 0)
                    createTbody.innerHTML = ` `;
                else
                    createTbody.innerHTML = rows.join('');


                // Append the tbody to your table
                // Replace 'your-table-id' with the actual ID of your table element
                document.getElementById('support-articlelists').appendChild(createTbody);

                document.getElementById('hideAfterloading')?.classList.add('d-none');
                document.getElementById('theadShow')?.classList.remove('d-none');

                // var myTable = document.querySelector("#support-category");

                $(document).ready(function() {

                    var SITEURL = '{{ url('') }}';

                    // Csrf field
                    $.ajaxSetup({
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        }
                    });

                    let prev = {!! json_encode(lang("Previous")) !!};
                    let next = {!! json_encode(lang("Next")) !!};
                    let nodata = {!! json_encode(lang("No data available in table")) !!};
                    let noentries = {!! json_encode(lang("No entries to show")) !!};
                    let showing = {!! json_encode(lang("showing page")) !!};
                    let ofval = {!! json_encode(lang("of")) !!};
                    let maxRecordfilter = {!! json_encode(lang("- filtered from ")) !!};
                    let maxRecords = {!! json_encode(lang("records")) !!};
                    let entries = {!! json_encode(lang("entries")) !!};
                    let show = {!! json_encode(lang("Show")) !!};
                    let search = {!! json_encode(lang("Search")) !!};
                    // Datatable
                    $('#support-articlelists').dataTable({
                        language: {
                            searchPlaceholder: search,
                            scrollX: "100%",
                            sSearch: '',
                            paginate: {
                            previous: prev,
                            next: next
                            },
                            emptyTable : nodata,
                            infoFiltered: `${maxRecordfilter} _MAX_ ${maxRecords}`,
                            info: `${showing} _PAGE_ ${ofval} _PAGES_`,
                            infoEmpty: noentries,
                            lengthMenu: `${show} _MENU_ ${entries} `,
                        },
                        order:[],
                        columnDefs: [
                            { "orderable": false, "targets":[ 0,1,4] }
                        ],
                    });

                    $('.form-select').select2({
                        minimumResultsForSearch: Infinity,
                        width: '100%'
                    });

                    $('.form-select').on('focus', function() {
                        $(this).attr('aria-hidden', 'false');
                    });
                });


                initializeTooltips();

                function initializeTooltips() {
                    var tooltipElements = document.querySelectorAll('[data-bs-toggle="tooltip"]');
                    tooltipElements.forEach(function(element) {
                        new bootstrap.Tooltip(element);
                    });
                }


            }

            $(function() {

                // Variables
                var SITEURL = '{{url('')}}';

                window.setColorPicker = (elem, defaultValue) => {
                    elem = document.querySelector(elem);
                    let pickr = Pickr.create({
                        el: elem,
                        default: defaultValue,
                        theme: 'nano', // or 'monolith', or 'nano'
                        useAsButton: true,
                        swatches: [
                            '#217ff3',
                            '#11cdef',
                            '#fb6340',
                            '#f5365c',
                            '#f7fafc',
                            '#212529',
                            '#2dce89'
                        ],
                        components: {
                            // Main components
                            preview: true,
                            opacity: true,
                            hue: true,
                            // Input / output Options
                            interaction: {
                                hex: true,
                                rgba: true,
                                // hsla: true,
                                // hsva: true,
                                // cmyk: true,
                                input: true,
                                clear: true,
                                silent: true,
                                preview: true,
                            }
                        }
                    });
                    pickr.on('init', pickr => {
                        elem.value = pickr.getSelectedColor().toRGBA().toString(0);
                    }).on('change', color => {
                        elem.value = color.toRGBA().toString(0);
                    });

                    return pickr;

                }
                // Color Pickr variables
                setTimeout(() => {
                    let themeColor = setColorPicker('#primary_color-input', document.querySelector('#primary_color-input')?.value);
                    let themeColorDark = setColorPicker('#secondary_color-input', document.querySelector('#secondary_color-input').value);
                }, 100);

                // Datepicker
                setTimeout(() => {
                    $('#startdate').datepicker({
                            dateFormat: 'yy-mm-dd',
                            prevText: '<i class="fa fa-angle-left"></i>',
                            nextText: '<i class="fa fa-angle-right"></i>',
                            minDate: 0,
                            firstDay: {{setting('start_week')}},

                            onSelect: function (selectedDate) {

                                var diff = ($("#enddate").datepicker("getDate") -
                                    $("#startdate").datepicker("getDate")) /
                                    1000 / 60 / 60 / 24 + 1; // days
                                if ($("#enddate").datepicker("getDate") != null) {
                                    $('#count').html(diff);
                                    $('#days').val(diff);
                                }
                                $('#enddate').datepicker('option', 'minDate', selectedDate);
                            }
                        });
                }, 100);
                setTimeout(() => {
                    $('#enddate').datepicker({
                        dateFormat: 'yy-mm-dd',
                        prevText: '<i class="fa fa-angle-left"></i>',
                        nextText: '<i class="fa fa-angle-right"></i>',
                        firstDay: {{setting('start_week')}},
                        onSelect: function (selectedDate) {

                            $('#startdate').datepicker('option', 'maxDate', selectedDate);

                            var diff = ($("#enddate").datepicker("getDate") -
                                $("#startdate").datepicker("getDate")) /
                                1000 / 60 / 60 / 24 + 1; // days
                            if ($("#startdate").datepicker("getDate") != null) {
                                $('#count').html(diff);
                                $('#days').val(diff);
                            }
                        }
                    });
                }, 100);

                // Holiday status change
                $('body').on('click', '.tswitch', function () {
                    var _id = $(this).data("id");
                    var status = $(this).prop('checked') == true ? '1' : '0';
                        $.ajax({
                            type: "post",
                            url: SITEURL + "/admin/holidays/statuschange/"+_id,
                            data: {'status': status},
                            success: function (data) {
                                toastr.success(data.success);
                            },
                            error: function (data) {
                                console.log('Error:', data);
                            }
                        });
                });

                //trigger next modal
                $("#addholidaymodal").on( "click", function() {
                    $('#Holidayform').trigger("reset");
                    $('#holiday_id').val("");
                    $('#occasion').val("");
                    $('#holidaydescription').html("");
                    $('#holidaysave').html("Add");
                    $('.modal-title').html("{{lang('Add Holiday Announcement')}}");
                    $('#holidaymodal').modal('show');

                });

                $('#holidaymodal').on('shown.bs.modal', function () {
                    $('#occasion').focus();
                });

                $('#holidaymodal').on('hidden.bs.modal', function () {
                    $('#Holidayform').trigger("reset");
                    $('#holiday_id').val("");
                });

                //edit holiday
                $('body').on('click', '#editholidaymodal', function () {
                    $('#Holidayform').trigger("reset");
                    var holiday_id = $(this).data('id');
                    $.get('holidays/' + holiday_id , function (data) {
                        $('#startdateError').html('');
                        $('#enddateError').html('');
                        $('.modal-title').html("{{lang('Edit Holiday Announcement')}}");
                        $('#holiday_id').val(data.id);
                        $('#occasion').val(data.occasion);
                        $('#startdate').val(data.startdate.substr(0, 10));
                        $('#enddate').val(data.enddate.substr(0, 10));
                        $('#holidaydescription').html(data.holidaydescription);
                        $('#primary_color-input').val(data.primaray_color);
                        $('#secondary_color-input').val(data.secondary_color);
                        document.querySelector("#holidaystatus").checked = data.status == 1 ? true : false
                        $('#holidaysave').html("Update");
                        $('#holidaymodal').modal('show');
                    });
                });

                //checkbox script
                $(document).ready(function() {

                    $(document).on('click', '#customCheckAll', function() {
                        $('.checkall').prop('checked', this.checked);
                        updateMassDeleteVisibility();
                    });

                    $(document).on('click', '.checkall', function() {
                        updateCustomCheckAll();
                        updateMassDeleteVisibility();
                    });


                    $(document).on('click', '.pagination a', function() {

                        setTimeout(function() {
                            updateMassDeleteVisibility();
                        }, 100);
                    });


                    $('#customCheckAll').prop('checked', false);


                    function updateMassDeleteVisibility() {
                        if ($('.checkall:checked').length == 0) {
                            $('#massdeletenotify').hide();
                        } else {
                            $('#massdeletenotify').show();
                        }
                    }


                    function updateCustomCheckAll() {
                        var totalCheckboxes = $('.checkall').length;
                        var checkedCheckboxes = $('.checkall:checked').length;

                        if (checkedCheckboxes === totalCheckboxes) {
                            $('#customCheckAll').prop('checked', true);
                        } else {
                            $('#customCheckAll').prop('checked', false);
                        }
                    }
                });

                $('body').on( "click" ,"#holidaysave", function() {
                    var form = document.getElementById('Holidayform');
                    var formData = new FormData(form);
                    formData.append('holidaydescription', document.getElementById('holidaydescription').textContent.trim());

                    $('#holidaysave').html('Sending ... <i class="fa fa-spinner fa-spin"></i>');
                    $.ajax({
                        type: "POST",
                        dataType: "json",
                        url: '{{route('saveholidays')}}',
                        data:formData,
                        cache:false,
                        contentType: false,
                        processData: false,

                        success:function(data){
                            console.log('success',data);
                            $('#holidaysave').html('Save Changes');
                            $('#holidaymodal').modal('hide');
                            toastr.success(data.success);
                            if ($.fn.DataTable.isDataTable('#support-articlelists')) {
                                $('#support-articlelists').DataTable().clear().destroy();
                            }
                            tableData = data.holidays;
                            loadTable(tableData);

                        },
                        error:function(data){
                            $('#holidaysave').html('Save Changes');
                            if(data?.responseJSON?.errors?.occasion){
                                $('#occasionError').html(data.responseJSON.errors.occasion);
                            }
                            if(data?.responseJSON?.errors?.startdate){
                                $('#startdateError').html(data.responseJSON.errors.startdate);
                            }
                            if(data?.responseJSON?.errors?.enddate){
                                $('#enddateError').html(data.responseJSON.errors.enddate);
                            }
                            if(data?.responseJSON?.errors?.holidaydescription){
                                $('#holidaydescriptionError').html(data.responseJSON.errors.holidaydescription);
                            }
                            if(data?.responseJSON?.errors?.primary_color){
                                $('#primary_colorError').html(data.responseJSON.errors.primary_color);
                            }
                            if(data?.responseJSON?.errors?.secondary_color){
                                $('#secondary_colorError').html(data.responseJSON.errors.secondary_color);
                            }
                        }
                    });
                });

                // Delete the Holiday
                $('body').on('click', '#deleteholidaymodal', function () {
                    let parent = $(this).closest('tr');
                    var holiday_id = $(this).data("id");

                    swal({
                        title: `{{lang('Are you sure you want to continue?', 'alerts')}}`,
                        text: "{{lang('This might erase your records permanently', 'alerts')}}",
                        icon: "warning",
                        buttons: true,
                        dangerMode: true,
                    })
                    .then((willDelete) => {
                        if (willDelete) {
                        $.get('holidays/delete/' + holiday_id , function (data) {
                            toastr.success('{{lang('successfully deleted .', 'alerts')}}');
                            $(parent[0]).addClass('fade-out');
                            let newData = tableData.filter(item => item.id != parseInt(holiday_id));
                            tableData = newData;
                            setTimeout(() => {
                                parent[0].remove();
                                if ($.fn.DataTable.isDataTable('#support-articlelists')) {
                                    $('#support-articlelists').DataTable().clear().destroy();
                                }
                                loadTable(tableData);
                            }, 1500);
                        });

                        }
                    });
                });

                // Mass Delete
                $('body').on('click', '#massdeletenotify', function () {
                    var parent = [];
                    var id = [];
                    $('.checkall:checked').each(function(){
                        parent.push($(this).closest('tr'));
                        id.push($(this).val());
                    });
                    if(id.length > 0){
                        swal({
                            title: `{{lang('Are you sure you want to continue?', 'alerts')}}`,
                            text: "{{lang('This might erase your records permanently', 'alerts')}}",
                            icon: "warning",
                            buttons: true,
                            dangerMode: true,
                        })
                        .then((willDelete) => {
                            if (willDelete) {
                                $.ajax({
                                    url:"{{ url('admin/holidays/massdelete')}}",
                                    method:"GET",
                                    data:{id:id},
                                    success:function(data)
                                    {
                                        $('#massdeletenotify').hide();

                                        toastr.success(data.success);
                                        parent.forEach(function(row) {
                                            row.addClass('fade-out');
                                        });
                                        let newData = tableData.filter(item => !id.includes(String(item.id)));
                                        tableData = newData;
                                        setTimeout(() => {
                                            parent.forEach(function(row) {
                                                row.remove();
                                            });
                                            if ($.fn.DataTable.isDataTable('#support-articlelists')) {
                                                $('#support-articlelists').DataTable().clear().destroy();
                                            }
                                            $('#customCheckAll').prop('checked', false);
                                            loadTable(tableData);
                                        }, 1500);
                                    },
                                    error:function(data){

                                    }
                                });
                            }
                        });
                    }else{
                        toastr.error('{{lang('Please select at least one check box.', 'alerts')}}');
                    }

                });
            })

            const textarea = document.getElementById("holidaydescription");
            let spellCheckEnabled = @json(setting('spellCheck'));
            let suggestionsEnabled = @json(setting('wordSuggestion'));

            if (spellCheckEnabled != 'off' || suggestionsEnabled != 'off') {

                let previousContent = "";
                let debounceTime;
                let latestInput = "";

                // Input event to process the text
                textarea.addEventListener("input", function () {
                    if(document.getElementById('suggestionText')){
                        document.getElementById('suggestionText').remove()
                    }
                    const userText = textarea.innerText.trim();
                    const currentSelection = window.getSelection();
                    const cursorAtEnd = currentSelection.rangeCount > 0 && currentSelection.getRangeAt(0).endOffset > 0 && textarea.innerText.length > 0;

                    // Fetch only when cursor is at the end and content has changed
                    if (cursorAtEnd && userText !== previousContent) {
                        previousContent = userText;
                        clearTimeout(debounceTime);

                        debounceTime = setTimeout(() => {
                            if (userText.length > 0) {
                                fetchCombinedRequest(userText);
                            }
                        }, 1000);
                    } else {
                        if(document.getElementById('suggestionText')){
                            document.getElementById('suggestionText').innerText = "";
                        }
                    }
                });

                async function fetchCombinedRequest(userInput) {
                    try {
                        let url = '{{ route('geminiGet') }}';
                        const response = await fetch(url, {
                            method: "POST",
                            headers: {
                                "Content-Type": "application/json",
                                'X-CSRF-TOKEN': '{{ csrf_token() }}'
                            },
                            body: JSON.stringify({ value: userInput }),
                        });

                        if (!response.ok) throw new Error("Failed to fetch");

                        const data = await response.json();

                        handleCombinedResponse(data.generated_text);
                    } catch (error) {
                        console.error("Error fetching data:", error);
                    }
                }

                // Function to handle combined response
                function handleCombinedResponse(responseText) {
                    if (spellCheckEnabled == 'on' && suggestionsEnabled == 'on') {
                        const spellCheckResponse = parseApiResponse(responseText); // Parse spell check response
                        const suggestionsResponse = responseText.match(/suggestion:\s*([a-zA-Z\s]+)/)?.[1];
                        if (spellCheckResponse) {
                            applyCorrections(spellCheckResponse);
                            placeCaretAtEnd();
                        }

                        // Display suggestions
                        if (suggestionsResponse) {
                            displaySuggestion(suggestionsResponse);
                        }
                    } else if (spellCheckEnabled == 'on' && suggestionsEnabled == 'off') {
                        const correctedText = parseApiResponse(responseText);
                        applyCorrections(correctedText);
                        placeCaretAtEnd();
                    } else if (suggestionsEnabled == 'on') {
                        displaySuggestion(responseText.trim());
                    }
                }

                function parseApiResponse(responseText) {
                    const corrections = {};
                    let formattedResponse = responseText.replace(/['"]+/g, "");
                    formattedResponse = formattedResponse.replace(/\n/g, ",");
                    const pairs = formattedResponse.split(",");
                    pairs.forEach(pair => {
                        const [misspelled, corrected] = pair.split(":").map(s => s.trim());
                        if (misspelled && corrected && misspelled != corrected) {
                            corrections[misspelled] = corrected;
                        }
                    });
                    return corrections;
                }

                function applyCorrections(corrections) {
                    let htmlContent = textarea.innerHTML;
                    Object.entries(corrections).forEach(([misspelled, corrected]) => {
                        const regex = new RegExp(`\\b${escapeRegExp(misspelled)}\\b`, 'gi');
                        htmlContent = htmlContent.replace(regex,
                            `<span class="misspelled" data-corrected="${corrected}">${misspelled}</span>`
                        );
                    });
                    textarea.innerHTML = htmlContent;
                    placeCaretAtEnd();
                }

                function displaySuggestion(responseApi) {
                    if(document.getElementById('suggestionText')){
                        document.getElementById('suggestionText').remove();
                    }

                    var suggestionTextData = document.createElement('span');
                    suggestionTextData.setAttribute('id','suggestionText');
                    suggestionTextData.innerHTML = responseApi.trim();

                    const selection = window.getSelection();
                    if (!selection || !selection.rangeCount) {
                        return;
                    }
                    document.getElementById('holidaydescription').append(suggestionTextData)
                }
                textarea.addEventListener('keydown', function (e) {
                    if (e.key === "Tab") {
                        e.preventDefault();

                        const suggestionTextData = document.getElementById('suggestionText');
                        if (suggestionTextData && suggestionTextData.innerText.trim().length > 0) {
                            let userInput = textarea.innerText.trim();
                            let suggestion = suggestionTextData.innerText.trim();
                            if (userInput.endsWith(suggestion)) {
                                userInput = userInput.slice(0, -suggestion.length).trim();
                            }
                            textarea.innerText = `${userInput} ${suggestion}`;
                            suggestionTextData.innerText = '';
                            if (suggestionTextData) {
                                suggestionTextData.remove();
                            }
                            placeCaretAtEnd();
                        }
                    }
                });

                function escapeRegExp(string) {
                    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
                }

                document.body.addEventListener('mouseover', function (event) {
                    const element = event.target;
                    if (element.classList.contains('misspelled')) {
                        showTooltip(event, element);
                    }
                });

                document.body.addEventListener('mouseout', function (event) {
                    const element = event.target;
                    const relatedTarget = event.relatedTarget;

                    if (element.classList.contains('misspelled')) {
                        if (relatedTarget && relatedTarget.classList.contains('correctedtooltip')) {
                            return;
                        }
                        hideTooltip();
                    } else if (element.classList.contains('correctedtooltip')) {
                        if (relatedTarget && relatedTarget.classList.contains('misspelled')) {
                            return;
                        }
                        hideTooltip();
                    }
                });

                function showTooltip(event, element) {
                    const correctedWord = element.getAttribute('data-corrected');
                    hideTooltip();

                    const tooltip = document.createElement('span');
                    tooltip.className = 'correctedtooltip';
                    tooltip.textContent = correctedWord;

                    // Styling
                    tooltip.style.backgroundColor = '#fff';
                    tooltip.style.border = '1px solid #ccc';
                    tooltip.style.padding = '5px';
                    tooltip.style.zIndex = '1000';
                    tooltip.style.boxShadow = '0px 2px 8px rgba(0, 0, 0, 0.2)';
                    tooltip.style.borderRadius = '4px';

                    element.parentNode.insertBefore(tooltip, element.nextSibling);

                    tooltip.onclick = (e) => {
                        e.stopPropagation();
                        replaceWord(element, correctedWord);
                    };

                    element.tooltip = tooltip;
                }

                function hideTooltip() {
                    const existingTooltip = document.querySelector('.correctedtooltip');
                    if (existingTooltip) {
                        existingTooltip.remove();
                    }
                }

                function replaceWord(element, correctedWord) {
                    const parent = element.parentElement;
                    if(parent.classList.contains('misspelled')){
                        parent.classList.remove('misspelled');
                    }
                    parent.innerHTML = parent.innerHTML.replace(
                        new RegExp(`<span[^>]*>${element.textContent}</span>`, 'gi'),
                        correctedWord
                    );
                    hideTooltip();
                    placeCaretAtEnd()
                }

                function placeCaretAtEnd() {
                    setTimeout(() => {
                        textarea.focus();
                        const range = document.createRange();
                        const selection = window.getSelection();
                        range.selectNodeContents(textarea);
                        range.collapse(false);
                        selection.removeAllRanges();
                        selection.addRange(range);
                    }, 1);
                }
            }
        });

    </script>
@endsection

