<style>
    #description .ql-editor {
        min-height: 350px;
    }
</style>
<div class="row">
    <div class="col-sm-12">
        <x-form id="letterForm">
            <div class="card bg-white rounded">
                <h4 class="mb-0 p-20 f-21 font-weight-normal border-bottom">
                    <div>Generate Document - {{$project->project_name}} - {{$project->category->category_name}} - {{$template->title}} </div>
                    <button id="downloadButton" type="button" class="btn btn-primary py-1 px-2 f-14 float-right">
                        @lang('letter::app.download')
                    </button>
                </h4>
                <div class="col-md-12 pb-2">
                    <x-forms.label class="my-3" fieldId="description-text" :fieldLabel="__('app.description')">
                    </x-forms.label>
                    <div id="description">{!! $letter?->description !!}</div>
                    <textarea name="description" id="description-text" class="d-none">{!! $letter?->description !!}</textarea>
                </div>


                {{-- <x-form-actions>
                    <x-forms.button-primary id="save-letter" icon="check">@lang('app.save')</x-forms.button-primary>
                    <x-forms.button-cancel :link="route('letter.generate.index')" class="border-0 mr-3">@lang('app.cancel')
                    </x-forms.button-cancel>

                </x-form-actions> --}}

            </div>


            <div>

            </div>
        </x-form>

    </div>

</div>

<script>
   $(document).ready(function() {
    quillImageLoad('#description');
    var employeeLetterVariable = @json($letterVariables);
    var quill = quillArray['#description'];

    function replaceVariables(content = '') {
        var result = content || quill.root.innerHTML;

        // Replace all letter variables inside the editor itself
        for (var [key, value] of Object.entries(employeeLetterVariable)) {
            if (value == null) {
                value = '--';
            }
            result = result.replaceAll(key, value);
        }

        quill.root.innerHTML = result;
    }
    $('#downloadButton').on('click', function() {
    var url = "{{ route('letter.download.preview.store') }}";

    $.easyAjax({
        url: url,
        type: "POST",
        data: {
            _token: "{{ csrf_token() }}",
            description: quill.root.innerHTML // Get the updated content from Quill
        },
        success: function(response) {
            if (response.url) {
                window.location.href = response.url; // Redirect to the generated file for download
            }
        }
    });
});

    function updateEmployeeVariables() {
        let employeeName = $('#employeeName').val();
        employeeLetterVariable['##EMPLOYEE_NAME##'] = employeeName;
        replaceVariables();
    }

    // Update padding settings
    function setEditorPadding() {
       
        $('.ql-editor').css({
            "padding-left": 20 + "px",
            "padding-right": 20 + "px",
            "padding-top": 20 + "px",
            "padding-bottom": 20 + "px"
        });
    }

    // On text change, update the hidden text area
    quill.on('text-change', function() {
        $('#description-text').val(quill.root.innerHTML);
    });

    // Handle employee selection changes
    $('#letterForm').on('change', '#employees', function() {
        var employeeId = $("#employees").val();
        employeeLetterVariable = {}; // Reset variables

        if (employeeId == '') {
            updateEmployeeVariables();
            return;
        }

        var url = "{{ route('letter.employee', ':id') }}";
        url = url.replace(':id', employeeId);

        $.easyAjax({
            url: url,
            type: "GET",
            container: '#letterForm',
            blockUI: true,
            redirect: true,
            success: function(response) {
                employeeLetterVariable = response.employeeLetterVariable;
                replaceVariables();
            }
        });
    });

    // Handle document template selection
    $('#letterForm').on('change', '#template_id', function() {
        var letterId = $("#template_id").val();
        var url = "{{ route('letter.ajax.template', ':id') }}";
        url = url.replace(':id', letterId);

        $.easyAjax({
            url: url,
            type: "GET",
            container: '#letterForm',
            blockUI: true,
            redirect: true,
            success: function(response) {
                quill.pasteHTML(response.letter.description);
                replaceVariables();
            }
        });
    });

    // Print functionality
    $('#printButton').on('click', function() {
        let printFrame = document.createElement('iframe');
        let html = '<html><head><title>Print</title><link type="text/css" rel="stylesheet" media="all" href="{{ asset('css/main.css') }}"></head>';
        html += '<body class="text-wrap ql-editor">';
        html += quill.root.innerHTML;
        html += '</body></html>';
        printFrame.style.display = 'none';
        document.body.appendChild(printFrame);

        printFrame.contentDocument.open();
        printFrame.contentDocument.write(html);
        printFrame.contentDocument.close();

        printFrame.onload = function() {
            printFrame.contentWindow.print();
            printFrame.contentWindow.onafterprint = function() {
                document.body.removeChild(printFrame);
            };
        };
    });

    // Save Letter
    $('#save-letter').click(function() {
        var url = "{{ route('letter.generate.store') }}";

        $.easyAjax({
            url: url,
            container: '#letterForm',
            type: "POST",
            blockUI: true,
            buttonSelector: "#save-letter",
            disableButton: true,
            data: $('#letterForm').serialize(),
        });
    });

    // Handle copy to clipboard functionality
    const clipboard = new ClipboardJS('.btn-copy');
    clipboard.on('success', function(e) {
        Swal.fire({
            icon: 'success',
            text: "{{ __('app.copied') }}",
            toast: true,
            position: 'top-end',
            timer: 3000,
            timerProgressBar: true,
            showConfirmButton: false,
        });
    });

    replaceVariables();
});

</script>
