<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 Email - {{$project->project_name}} - {{$project->category->category_name}} - {{$template->title}} </div>
                    <button type="button" class="btn btn-danger float-right" id="sendEmailButton">
                        @lang('Send Email')
                    </button>
                </h4>
               
              
                <div class="row px-3 pt-3">
                    <div class="col-sm-6">
                        <div class="form-group ">
                            <label for="emailTo">@lang('To')</label>
                            <input type="email" class="form-control height-35 f-14" id="emailTo" name="to" required>
                        </div>    
                    </div>
                    <div class="col-sm-6">

                        <div class="form-group">
                            <label for="emailCc">@lang('CC')</label>
                            <input type="email" class=" form-control height-35 f-14" id="emailCc" name="cc">
                        </div>
                    </div>
                    <div class="col-sm-6">
                        <div class="form-group">
                            <label for="emailSubject">@lang('Subject')</label>
                            <input type="text" class=" form-control height-35 f-14" id="emailSubject" name="subject">
                        </div>
    
                    </div>
                    
                </div>


                <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>

                <div class="col-sm-12 pt-5">

                    <div class="form-group">
                        <h4> <label><strong>@lang('Attach Documents')</strong></label> 
                            <button  id="loadDocumentsButton" type="button" class="btn btn-primary py-1 px-2 f-14 float-right">
                                @lang('Attach Documents')
                            </button>
                        </h4>
                       


                        <div id="projectFiles"></div>
                    </div>
                
                </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>
        <form id="emailForm" method="POST"></form>

    </div>

</div>


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

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

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

            descriptionPreview.html(result);
            setPreviewPadding();
        }

        function setEmployeeName() {
            let employeeName = $('#employeeName').val();
            employeeLetterVariable['##EMPLOYEE_NAME##'] = employeeName;
            generatePreview();
            $('#employeeNameField').removeClass('d-none');
        }

        function setPreviewPadding() {
            let left = $('#left').val() || 0;
            let right = $('#right').val() || 0;
            let top = $('#top').val() || 0;
            let bottom = $('#bottom').val() || 0;

            descriptionPreview.css({
                "padding-left": left + "px",
                "padding-right": right + "px",
                "padding-top": top + "px",
                "padding-bottom": bottom + "px"
            });
        }

        quill.on('text-change', function() {
            $('#description-text').val(quill.root.innerHTML);
            generatePreview();
        });

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

            $.easyAjax({
                url: url,
                type: "POST",
                data: {
                    _token: "{{ csrf_token() }}",
                    description: $('#descriptionPreviewArea').html()
                },
                success: function(response) {
                    window.location.href = response.url;
                }
            });

        });

        $('#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') }}"></';
            html += 'head><body class="text-wrap ql-editor">';
            html += $('#descriptionPreviewArea').html();
            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);
                };
            };
        });

        $('#letterForm').on('input', '#left, #right, #top, #bottom', function() {
            setPreviewPadding();
        });

        $('#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);
                    generatePreview();
                }
            });
        });

        $('body').on('input', '#employeeName', function() {
            setEmployeeName();
        });

        $('#letterForm').on('change', '#employees', function() {
            var employeeId = $("#employees").val();
            employeeLetterVariable = {};

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

            $('#employeeNameField').addClass('d-none');

            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;
                    generatePreview();
                }
            });
        });

        $('#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(),
            });
        });

        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,
                customClass: {
                    confirmButton: 'btn btn-primary',
                },
                showClass: {
                    popup: 'swal2-noanimation',
                    backdrop: 'swal2-noanimation'
                },
            })
        });

        generatePreview();

        init(RIGHT_MODAL);

    function loadProjectFiles() {
        var projectId = "{{ $project->id ?? '' }}";
        var url = "{{ route('project.documents', ':id') }}";
        url = url.replace(':id', projectId);

        $.ajax({
            url: url,
            type: "GET",
            success: function(response) {
                let filesHtml = '';
                response.files.forEach(file => {
                    filesHtml += `
                    <div class="col-sm-6">
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" id="id-${file.id}" type="checkbox" name="attachments[]" value="${file.id}">
                            <label class="form-check-label" for="id-${file.id}">${file.filename}</label>
                        </div>
                    </div>`;
                });
                $('#projectFiles').html(filesHtml);
            }
        });
    }

    function getUserSignature() {
        $.ajax({
            url: "{{ route('user.signature') }}",
            type: "GET",
            success: function(response) {
                $('#emailSignature').html(response.signature);
            }
        });
    }

    $('#loadDocumentsButton').on('click', function() {
        loadProjectFiles();
    });
    $('#sendEmailButton').on('click', function() {
        var emailTo = $('#emailTo').val().trim();
        var emailSubject = $('#emailSubject').val().trim();

        // Validate required fields
        if (!emailTo) {
            Swal.fire({
                icon: 'error',
                text: "The 'To' field is required.",
                toast: true,
                position: 'top-end',
                timer: 3000,
                showConfirmButton: false
            });
            return;
        }

        if (!emailSubject) {
            Swal.fire({
                icon: 'error',
                text: "The 'Subject' field is required.",
                toast: true,
                position: 'top-end',
                timer: 3000,
                showConfirmButton: false
            });
            return;
        }

        // Confirmation popup before submitting form
        Swal.fire({
            title: "Are you sure?",
            text: "Do you want to send this email?",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
            confirmButtonText: "Yes, send it!"
        }).then((result) => {
            if (result.isConfirmed) {
                // Set the form action
                var form = $('#emailForm');
                form.attr('action', "{{ route('outlook.sendEmail') }}");
                form.attr('method', "POST");

                // Append hidden fields for additional data
                $('<input>').attr({
                    type: 'hidden',
                    name: 'to',
                    value: emailTo
                }).appendTo(form);

                $('<input>').attr({
                    type: 'hidden',
                    name: 'cc',
                    value: $('#emailCc').val()
                }).appendTo(form);

                $('<input>').attr({
                    type: 'hidden',
                    name: 'subject',
                    value: emailSubject
                }).appendTo(form);
                $('<input>').attr({
                    type: 'hidden',
                    name: 'message',
                    value: quill.root.innerHTML
                }).appendTo(form);
                console.log('in here 2');
               
                // Append attachments
                $('input[name="attachments[]"]:checked').each(function() {
                    $('<input>').attr({
                        type: 'hidden',
                        name: 'attachments[]',
                        value: $(this).val()
                    }).appendTo(form);
                });

                // Append CSRF token if needed
                $('<input>').attr({
                    type: 'hidden',
                    name: '_token',
                    value: "{{ csrf_token() }}"
                }).appendTo(form);
                console.log('in here 3');
               
                // Submit the form
                form.submit();
                console.log('in here 4');
               
            }
        });
    });

});

</script>
