<% function formatDate(dateStr) { if (!dateStr) return '' ; const d=new Date(dateStr); const yyyy=d.getFullYear(); const
    mm=String(d.getMonth() + 1).padStart(2, '0' ); const dd=String(d.getDate()).padStart(2, '0' ); return
    `${yyyy}-${mm}-${dd}`; } %>
    <div class="page-header">
    <h3 class="page-title">Edit Template</h3>
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="/" class="text-decoration-none">Dashboard</a></li>
            <li class="breadcrumb-item"><a href="/templates" class="text-decoration-none">Templates</a></li>
            <li class="breadcrumb-item active" aria-current="page">Edit Template</li>
        </ol>
    </nav>
</div>
    <div class="card">
        <div class="card-body">
            <p class="card-description">Please provide the required information. * indicates required field.</p>
            <form class="forms-sample" id="myForm" method="post" action="/templates/edit/<%=data?._id%>">
                <div class="row">
                    <div class="col-lg-6">
                        <div class="form-group">
                            <label for="title">Title *</label>
                            <input type="text" class="form-control" id="title" name="title"
                                placeholder="Please enter value here" value="<%=data?.title ?? ''%>">
                        </div>
                    </div>
                    <div class="col-lg-6">
                        <div class="form-group">
                            <label for="subject">Subject *</label>
                            <input type="text" class="form-control" id="subject" name="subject"
                                placeholder="Please enter value here" value="<%=data?.subject ?? ''%>">
                        </div>
                    </div>
                    <div class="col-lg-6">
                        <div class="form-group">
                            <label for="shortCodes" class="d-block">Short Codes (Click to copy & paste it in the body.
                                The value will be replaced while this template is used).</label>
                            <% shortCodes.forEach((shortCode)=> { %>
                                <span class="badge badge-success" style="font-weight: bold; cursor: pointer;"
                                    onclick="copyText(this)">
                                    <%=shortCode%>
                                </span>
                                <% }) %>
                        </div>
                    </div>
                    <div class="col-lg-12">
                        <div class="form-group">
                            <label for="body">Body *</label>
                            <input type="hidden" id="body" name="body" value="<%=data?.body ?? ''%>">
                            <div class="form-control" id="bodyEditor" style="height: 400px;">
                                <%-data?.body ?? '' %>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-12">
                        <div class="form-group">
                            <label for="attachments">Attachments</label>
                            <div class="file-input-wrapper border-end" data-count="No file selected">
                                <input class="form-control" type="file" id="attachments" multiple>
                            </div>
                            <ul class="files-preview mx-0 p-0 mt-2" id="files-preview">
                            </ul>
                        </div>
                    </div>

                    <div class="col-lg-12">
                        <div class="form-group">
                            <label for="status">Status</label>
                            <select class="form-select rounded-0" id="status" name="status"
                                aria-label="Default select example">
                                <%-dropdowns?.status%>
                            </select>
                        </div>
                        <div class="col-lg-6">
                            <div class="form-group">
                                <label for="description">Description</label>
                                <input type="text" class="form-control" id="description" name="description"
                                    placeholder="Please enter value here" value="<%=data?.description ?? ''%>">
                            </div>
                        </div>
                    </div>
                </div>

                <button type="submit" class="btn btn-gradient-primary me-2">Submit</button>
                <a href="/templates" class="btn btn-light">Cancel</a>
            </form>
        </div>
    </div>

    <script>
        $(document).ready(function () {
            const quill = new Quill('#bodyEditor', {
                theme: 'snow',
                modules: {
                    toolbar: toolbarOptions
                }
            });

            quill.on('text-change', function () {
                const html = quill.root.innerHTML;
                document.getElementById('body').value = html;
            });
            $("#myForm").validate({
                errorElement: 'span',
                errorClass: 'is-invalid',
                validClass: 'is-valid',
                rules: {
                    title: {
                        required: true,
                        minlength: 2,
                        maxlength: 100
                    },
                    subject: {
                        required: true,
                        minlength: 2,
                        maxlength: 200
                    },
                    body: {
                        required: true,
                        minlength: 2,
                        maxlength: 50000
                    },
                },
                messages: {
                    title: {
                        required: "Please enter your title.",
                        minlength: "Name must be at least 2 characters."
                    },
                },
                success: function (label, element) {
                    const $el = $(element);
                    const value = $el.val().trim();

                    if (value === '') {
                        $el.removeClass('is-valid');
                    }
                },

                highlight: function (element) {
                    $(element).removeClass('is-valid').addClass('is-invalid');
                },

                unhighlight: function (element) {
                    const $el = $(element);
                    const value = $el.val().trim();

                    if (value !== '') {
                        $el.removeClass('is-invalid').addClass('is-valid');
                    } else {
                        $el.removeClass('is-valid is-invalid');
                    }
                },
                submitHandler: function (form) {
                    const formData = new FormData();
                    formData.append('title', $('#title').val());
                    formData.append('status', $('#status').val());
                    formData.append('subject', $('#subject').val());
                    formData.append('body', $('#body').val());
                    formData.append('description', $('#description').val());
                    const newFiles = window.selectedAttachments.filter(file => !file.oldAttachment);
                    const deletedFiles = window.deletedAttachments;
                    if (newFiles && newFiles.length) {
                        newFiles.forEach((file, i) => {
                            formData.append(`attachments`, file);
                        });
                    }
                    formData.append(`deletedFiles`, JSON.stringify(deletedFiles));

                    $.ajax({
                        url: `/templates/edit/<%=data?._id%>`,
                        method: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function (response) {
                            // alert("Emails sent successfully!");
                            setLocal(response.success ? "success_msg" : "error_msg", response.message);
                            window.location.href = '/templates';
                        },
                        error: function (xhr) {
                            // Show error message
                            $('#result').html('<p style="color:red;">Error: ' + xhr.responseText + '</p>');
                        }
                    });
                }
            });
            $('#attachments').on('input', function (e) {
                const files = [];
                if (window.selectedAttachments && window.selectedAttachments.length) {
                    files.push(...window.selectedAttachments);
                }
                files.push(...Object.values(e.target.files));
                window.selectedAttachments = files;
                renderPreview();
            });
            renderPreview();
        });
        window.selectedAttachments = JSON.parse('<%-JSON.stringify(data?.attachments)%>').map(a => ({ ...a, oldAttachment: true }));
        function renderPreview() {
            let html = "";
            const files = window.selectedAttachments || [];
            files.forEach((file, i) => {
                html += `<li class="m-1">
                        <div class="position-relative bg-gradient-primary text-white">
                            <span class="d-block">${file.name}</span>
                            <span class="close-btn" onclick="removeAttachment('${i}', ${file.oldAttachment})">
                                <i class="fa fa-times-circle" aria-hidden="true"></i>
                            </span>
                        </div>
                    </li>`;
            });
            $("#files-preview").html(html);
            if (!files.length) {
                $("#attachments").parent().attr("data-count", "No file selected");
            } else {
                $("#attachments").parent().attr("data-count", `${files.length} ${files.length == 1 ? "file" : "files"} selected`);
            }
            $("#attachments").val("");
        }
        window.deletedAttachments = [];
        function removeAttachment(i, isOld = false) {
            if (isOld) {
                let files = window.selectedAttachments;
                window.deletedAttachments.push(files[i].name);
                files.splice(i, 1);
                window.selectedAttachments = files;
                renderPreview();
            } else {
                let files = window.selectedAttachments;
                files.splice(i, 1);
                window.selectedAttachments = files;
                renderPreview();
            }
        }
    </script>