{% extends 'layout.twig' %}

{% block body %}
    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
    {% include 'nav.twig' %}

    <div class="container my-4">

        <!-- Card container -->
        <div class="card shadow">
            <div class="card-header bg-primary text-white">
                <h4 class="mb-0">Mass Email</h4>
            </div>
            <div class="card-body">

                <form id="emailForm" method="post" action="mass_email.php" enctype="multipart/form-data">
                    <!-- Hidden field for storing Quill’s HTML content -->
                    <input type="hidden" name="content">

                    <!-- SUBJECT -->
                    <div class="form-group">
                        <label for="subject"><strong>Subject</strong></label>
                        <input type="text" class="form-control" id="subject" name="subject" placeholder="Email Subject">
                    </div>

                    <!-- CONTENT (Quill Editor) -->
                    <div class="form-group">
                        <label for="editor2"><strong>Content</strong></label>
                        <div id="editor2" style="height: 25vh"></div>
                    </div>

                    <!-- ATTACHMENT -->
                    <div class="form-group">
                        <label for="fileUpload"><strong>Email Attachment</strong></label>
                        <input type="file" class="form-control-file" id="fileUpload" name="emailattachment">
                    </div>

                    <!-- RECIPIENT SELECTION -->
                    <div class="my-4">
                        <div class="custom-control custom-checkbox mb-2">
                            <input type="checkbox" class="custom-control-input" id="checkMembers" onclick="select_members(this)">
                            <label class="custom-control-label" for="checkMembers">All Members</label>
                        </div>
                        <div class="custom-control custom-checkbox mb-4">
                            <input type="checkbox" class="custom-control-input" id="checkAlumni" onclick="select_alumni(this)">
                            <label class="custom-control-label" for="checkAlumni">All Alumni</label>
                        </div>

                        <!-- MEMBER LIST -->
                        <h5 class="mt-2">Members</h5>
                        {% for i in members %}
                            <div class="custom-control custom-checkbox">
                                <input type="checkbox" class="custom-control-input member" id="member_{{ i.id }}" name="{{ i.id }}">
                                <label class="custom-control-label" for="member_{{ i.id }}">{{ i.name }}</label>
                            </div>
                        {% endfor %}

                        <!-- SEND BUTTON -->
                        <button type="button" id="uploadButton" class="btn btn-success btn-lg btn-block mt-4">
                            Upload &amp; Send
                        </button>

                        <!-- ALUMNI LIST -->
                        <h5 class="mt-4">Alumni</h5>
                        {% for i in alumni %}
                            <div class="custom-control custom-checkbox">
                                <input type="checkbox" class="custom-control-input alumni" id="alumni_{{ i.id }}" name="{{ i.id }}">
                                <label class="custom-control-label" for="alumni_{{ i.id }}">{{ i.name }}</label>
                            </div>
                        {% endfor %}
                    </div>

                    <!-- SEND BUTTON -->
                    <button type="button" id="uploadButton" class="btn btn-success btn-lg btn-block mt-4">
                        Upload &amp; Send
                    </button>
                </form>

            </div>
        </div>
    </div>
{% endblock %}

{% block script %}
    <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
    <script>
        // Initialize Quill editor
        var quill2 = new Quill('#editor2', {
            theme: 'snow'
        });

        // Convert Quill delta to HTML
        function quillGetHTML(inputDelta) {
            var tempCont = document.createElement("div");
            (new Quill(tempCont)).setContents(inputDelta);
            return tempCont.getElementsByClassName("ql-editor")[0].innerHTML;
        }

        // Update hidden input with Quill content
        function update_content() {
            var content = quill2.getContents();
            document.querySelector("input[name='content']").value = quillGetHTML(content);
        }

        // Select/deselect all members
        function select_members(which) {
            document.querySelectorAll(".member").forEach(function(checkbox) {
                checkbox.checked = which.checked;
            });
        }

        // Select/deselect all alumni
        function select_alumni(which) {
            document.querySelectorAll(".alumni").forEach(function(checkbox) {
                checkbox.checked = which.checked;
            });
        }

        // Chunked file uploader
        async function uploadFile(file) {
            const chunkSize = 1024 * 1024; // 1MB
            const totalChunks = Math.ceil(file.size / chunkSize);

            for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {
                const start = chunkIndex * chunkSize;
                const end = Math.min(file.size, start + chunkSize);
                const fileChunk = file.slice(start, end);

                const formData = new FormData();
                formData.append('fileChunk', fileChunk);
                formData.append('chunkIndex', chunkIndex);
                formData.append('totalChunks', totalChunks);
                formData.append('fileName', file.name);

                try {
                    const response = await fetch('api.php?method=upload_email_attachment', {
                        method: 'POST',
                        body: formData
                    });
                    const result = await response.json();
                    if (!result || result.status !== 200) {
                        throw new Error(`Error uploading chunk ${chunkIndex + 1}: ${result ? result.message : 'Unknown error'}`);
                    }
                } catch (error) {
                    console.error('Error uploading chunk', chunkIndex, error);
                    throw error; // Stop further uploads on error
                }
            }

            console.log('File upload complete');
        }

        // On "Upload & Send" click:
        document.getElementById('uploadButton').addEventListener('click', async function () {
            // First, store the Quill editor content
            update_content();

            const fileInput = document.getElementById('fileUpload');
            const file = fileInput.files[0];

            // If user selected a file, upload in chunks first
            if (file) {
                try {
                    await uploadFile(file);
                    console.log('File successfully uploaded');
                    document.getElementById('emailForm').submit();
                } catch (error) {
                    alert("File did not upload. Please try again.");
                    console.error('File upload failed:', error);
                }
            } else {
                // If no file, just submit
                document.getElementById('emailForm').submit();
            }
        });
    </script>
{% endblock %}
