/**
 * Message to Students JS
 * 
 * Handles UI interactions, AJAX requests, and batch message sending.
 */

$(document).ready(function () {
    // Initialize TinyMCE
    tinymce.init({
        selector: '#message_editor',
        height: 400,
        menubar: true,
        plugins: [
            'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
            'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
            'insertdatetime', 'media', 'table', 'help', 'wordcount', 'emoticons',
            'directionality', 'image', 'code', 'table'
        ],
        toolbar: 'undo redo | blocks fontfamily fontsize | ' +
            'bold italic underline forecolor backcolor | alignleft aligncenter ' +
            'alignright alignjustify | bullist numlist outdent indent | ' +
            'ltr rtl | emoticons charmap | removeformat | preview fullscreen code | help',
        content_style: 'body { font-family:Inter,Urdu Typo,sans-serif; font-size:16px; direction: rtl; }',
        language: 'en'
    });

    const $darjaSelect = $('#darja_select');
    const $studentListContainer = $('#student_list_container');
    const $messageContainer = $('#message_composition_container');
    const $studentTableBody = $('#student_table_body');
    const $checkAll = $('#check_all');
    const $uncheckAll = $('#uncheck_all');
    const $sendBtn = $('#send_message');
    const $loader = $('#loader');
    const $progressContainer = $('#progress_container');
    const $progressBar = $('#progress_bar');
    const $progressPercent = $('#progress_percent');
    const $progressLabel = $('#progress_label');

    // Fetch students on Darja change
    $darjaSelect.on('change', function () {
        const darja = $(this).val();
        if (!darja) {
            $studentListContainer.addClass('d-none');
            $messageContainer.addClass('d-none');
            $checkAll.addClass('d-none');
            $uncheckAll.addClass('d-none');
            return;
        }

        $loader.removeClass('d-none');
        $.ajax({
            url: 'APIs/message_to_students.php',
            type: 'GET',
            data: { action: 'fetchStudents', darja: darja },
            dataType: 'json',
            success: function (response) {
                $loader.addClass('d-none');
                if (response.success) {
                    renderStudents(response.students);
                    $studentListContainer.removeClass('d-none');
                    $messageContainer.removeClass('d-none');
                    $checkAll.removeClass('d-none');
                    $uncheckAll.removeClass('d-none');
                } else {
                    Swal.fire('Error', response.message, 'error');
                }
            },
            error: function () {
                $loader.addClass('d-none');
                Swal.fire('Error', 'Failed to connect to server', 'error');
            }
        });
    });

    function renderStudents(students) {
        $studentTableBody.empty();
        if (students.length === 0) {
            $studentTableBody.append('<tr><td colspan="4" class="text-center py-4">اس درجہ میں کوئی طالب علم موجود نہیں ہے۔</td></tr>');
            return;
        }

        students.forEach((std, index) => {
            $studentTableBody.append(`
                <tr>
                    <td class="text-center">${index + 1}</td>
                    <td>${std.stdName}</td>
                    <td>${std.fatherName}</td>
                    <td class="text-center">
                        <input type="checkbox" class="form-check-input std-checkbox" value="${std.sno}" 
                               data-email="${std.email || ''}" data-phone="${std.cellNo || ''}">
                    </td>
                </tr>
            `);
        });
    }

    // Check All / Uncheck All
    $checkAll.on('click', function () {
        $('.std-checkbox').prop('checked', true);
    });

    $uncheckAll.on('click', function () {
        $('.std-checkbox').prop('checked', false);
    });

    // Send Message
    $sendBtn.on('click', function () {
        const darja = $darjaSelect.val();
        const selectedStudents = [];
        $('.std-checkbox:checked').each(function () {
            selectedStudents.push({
                sno: $(this).val(),
                email: $(this).data('email'),
                phone: $(this).data('phone')
            });
        });

        const message = tinymce.get('message_editor').getContent();
        const sendEmail = $('#send_email').is(':checked');
        const sendWhatsapp = $('#send_whatsapp').is(':checked');

        // Validations
        if (!darja) return Swal.fire('Error', 'براہ کرم درجہ منتخب کریں۔', 'warning');
        if (selectedStudents.length === 0) return Swal.fire('Error', 'براہ کرم کم از کم ایک طالب علم کا انتخاب کریں۔', 'warning');
        if (!message) return Swal.fire('Error', 'براہ کرم پیغام تحریر کریں۔', 'warning');
        if (!sendEmail && !sendWhatsapp) return Swal.fire('Error', 'براہ کرم ارسال کرنے کا کم از کم ایک طریقہ منتخب کریں۔', 'warning');

        $sendBtn.prop('disabled', true);
        $loader.removeClass('d-none');
        $progressContainer.removeClass('d-none');
        resetProgress();

        let current = 0;
        const total = selectedStudents.length;

        // Start batch process
        processBatch(selectedStudents, message, sendEmail, sendWhatsapp);
    });

    function processBatch(students, message, sendEmail, sendWhatsapp) {
        $.ajax({
            url: 'APIs/message_to_students.php',
            type: 'POST',
            data: {
                action: 'sendMessages',
                students: JSON.stringify(students),
                message: message,
                send_email: sendEmail,
                send_whatsapp: sendWhatsapp
            },
            dataType: 'json',
            xhr: function () {
                var xhr = new window.XMLHttpRequest();
                // We use a custom header to track progress if the server supports it, 
                // but since it's a standard PHP process, we'll rely on the final response.
                // For a more dynamic progress, one would send messages one by one or in small chunks.
                // Given the instructions, we'll do it in one API call but with feedback.
                return xhr;
            },
            success: function (response) {
                updateProgress(100, 'عمل مکمل ہو گیا۔');
                $sendBtn.prop('disabled', false);
                $loader.addClass('d-none');

                if (response.success) {
                    Swal.fire({
                        title: 'کامیابی',
                        html: `میرا پیغام ${response.results.success} طلباء کو کامیابی سے بھیج دیا گیا ہے۔<br>
                               ${response.results.failure > 0 ? `<div class="text-danger mt-2">${response.results.failure} طلباء کو پیغام بھیجنے میں ناکامی ہوئی۔</div>` : ''}
                               <div class="mt-3"><small>لاگ فائل: <code>${response.logFile}</code></small></div>`,
                        icon: 'success'
                    });
                } else {
                    Swal.fire('خرابی', response.message, 'error');
                }
            },
            error: function () {
                $sendBtn.prop('disabled', false);
                $loader.addClass('d-none');
                Swal.fire('Error', 'سرور سے رابطہ ختم ہو گیا یا عمل میں خرابی آئی۔', 'error');
            }
        });
    }

    function resetProgress() {
        $progressBar.css('width', '0%');
        $progressPercent.text('0%');
        $progressLabel.text('پیغام بھیجے جا رہے ہیں...');
    }

    function updateProgress(percent, label) {
        $progressBar.css('width', percent + '%');
        $progressPercent.text(percent + '%');
        if (label) $progressLabel.text(label);
    }
});
