$(function() {
    let totalFiles = 0;
    let uploadedFiles = 0;

    $(document).on('click', ".delete_preview", function(e) {
        image_field = $(this).closest('.file_preview-container').prev('.images');
        image_field.val(image_field.val().replace(',' + $(this).attr("value"), ""));
        $(this).parent().remove();
    });

    $(document).on('change', "#file-input", function(e) {
        file_field = $(this).next('.images');
        let files = this.files;
        if (!files.length) return;

        totalFiles = files.length;
        uploadedFiles = 0;
        $("#send_icon").prop("disabled", true).removeClass("enabled");

        $.each(files, function(i, file) {
            let id = "file-" + Math.random().toString(36).substr(2, 9);

            if (file.type === "application/pdf") {
                $("#file_preview-container").show();
                $("#file_preview-container").append('<div class="file_preview nosort" data-img="' + file.name + '" id="' + id + '"><div class="file">📄</div> <div class="progress-circle">0%</div></div>');
            } else {
                let reader = new FileReader();
                reader.onload = function(e) {
                    $("#file_preview-container").show();
                    $("#file_preview-container").append('<div class="file_preview nosort" data-img="' + file.name + '" id="' + id + '"> <img src="' + e.target.result + '" alt="' + file.name + '"><div class="progress-circle">0%</div></div>');
                }
                reader.readAsDataURL(file);
            }

            uploadFile(file, id, file_field);
        });

        $("#file-input").val("");
    });

    function uploadFile(file, file_previewId, file_field) {
        let formData = new FormData();
        formData.append("files[]", file);

        $.ajax({
            xhr: function() {
                let xhr = new window.XMLHttpRequest();
                xhr.upload.addEventListener("progress", function(e) {
                    if (e.lengthComputable) {
                        let percent = Math.round((e.loaded / e.total) * 100);
                        $("#" + file_previewId + " .progress-circle").text(percent + "%");
                    }
                });
                return xhr;
            },
            url: "upload_files.php",
            type: "POST",
            data: formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function(resp) {
                if (Array.isArray(resp) && resp[0] && resp[0].success) {
                    file_field.val(file_field.val() + ',' + resp[0].file);
                    $("#" + file_previewId + " .progress-circle").text("✔️").css("background", "rgba(0,150,0,0.7)");
                    $("#" + file_previewId).append("<div class='file_name_preview'>" + resp[0].file_title + "</div>");
                    $("#" + file_previewId).append("<div value='" + resp[0].file + "' class='delete_preview'>حذف</div>");
                } else {
                    $("#" + file_previewId + " .progress-circle").text("❌").css("background", "rgba(200,0,0,0.7)");
                }
                uploadedFiles++;
                checkAllUploaded();
            },
            error: function(xhr, status, error) {
                console.log("AJAX Error:", status, error, xhr.responseText);
                $("#" + file_previewId + " .progress-circle").text("❌").css("background", "rgba(200,0,0,0.7)");
                uploadedFiles++;
                checkAllUploaded();
            }
        });
    }





    // ✅ الصور — أهم تعديل هنا ✅
    $(document).on('change', "#image-input , #add_ques_message_images , #edit_ques_message_images , #add_option_message_images , #edit_option_message_images", function(e, data) {

        image_field = $(this).next('.images');
        image_preview_cont = $(this).parent().find('.file_preview-container');
        current_message_body = $(this).closest('.message_body');

        let files = data?.droppedFiles || this.files;
        if (!files.length) return;

        totalFiles = files.length;
        uploadedFiles = 0;
        $("#send_icon").prop("disabled", true).removeClass("enabled");

        $.each(files, function(i, file) {
            let id = "file-" + Math.random().toString(36).substr(2, 9);

            if (file.type === "application/pdf") {
                image_preview_cont.show();
                image_preview_cont.append('<div class="file_preview nosort" data-img="' + file.name + '" id="' + id + '"><div class="progress-circle">0%</div></div>');
                current_message_body.scrollTop(current_message_body[0].scrollHeight);
            } else {
                let reader = new FileReader();
                reader.onload = function(e) {
                    image_preview_cont.show();
                    image_preview_cont.append('<div class="file_preview nosort" data-img="' + file.name + '" id="' + id + '"><img src="' + e.target.result + '" alt="' + file.name + '"><div class="progress-circle">0%</div></div>');
                    current_message_body.scrollTop(current_message_body[0].scrollHeight);
                }
                reader.readAsDataURL(file);
            }

            uploadImage(file, id, image_field);
        });

        $(this).val("");
    });


    function uploadImage(file, file_previewId, image_field) {
        let formData = new FormData();
        formData.append("files[]", file);

        $.ajax({
            xhr: function() {
                let xhr = new window.XMLHttpRequest();
                xhr.upload.addEventListener("progress", function(e) {
                    if (e.lengthComputable) {
                        let percent = Math.round((e.loaded / e.total) * 100);
                        $("#" + file_previewId + " .progress-circle").text(percent + "%");
                    }
                });
                return xhr;
            },
            url: "upload_images.php",
            type: "POST",
            data: formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function(resp) {
                if (Array.isArray(resp) && resp[0] && resp[0].success) {
                    image_field.val(image_field.val() + ',' + resp[0].file);
                    $("#" + file_previewId + " .progress-circle").text("✔️").css("background", "rgba(0,150,0,0.7)");
                    $("#" + file_previewId).append("<div class='file_name_preview'>" + resp[0].file_title + "</div>");
                    $("#" + file_previewId).append("<div value='" + resp[0].file + "' class='delete_preview'>x</div>");
                    $(".file_preview[data-img='" + resp[0].file_title + "']").attr('data-img', resp[0].file).removeClass('nosort');
                } else {
                    $("#" + file_previewId + " .progress-circle").text("❌").css("background", "rgba(200,0,0,0.7)");
                }
                uploadedFiles++;
                checkAllUploaded();
            },
            error: function(xhr, status, error) {
                console.log("AJAX Error:", status, error, xhr.responseText);
                $("#" + file_previewId + " .progress-circle").text("❌").css("background", "rgba(200,0,0,0.7)");
                uploadedFiles++;
                checkAllUploaded();
            }
        });
    }




    function checkAllUploaded() {
        if (uploadedFiles === totalFiles) {
            $("#send_icon").prop("disabled", false).addClass("enabled");
        }
    }

    $("#edit_ques_preview_sortable").sortable({
        cancel: ".nosort",
        update: function() {
            var orderedImages = [];
            $("#edit_ques_preview_sortable .file_preview").each(function() {
                orderedImages.push($(this).data("img"));
            });
            $("#edit_ques_message_images_text").val("," + orderedImages.join(","));
        }
    });
	
	$("#add_ques_preview_sortable").sortable({
        cancel: ".nosort",
        update: function() {
            var orderedImages = [];
            $("#add_ques_preview_sortable .file_preview").each(function() {
                orderedImages.push($(this).data("img"));
            });
            $("#add_ques_message_images_text").val("," + orderedImages.join(","));
        }
    });
	
	$("#edit_option_preview_sortable").sortable({
        cancel: ".nosort",
        update: function() {
            var orderedImages = [];
            $("#edit_option_preview_sortable .file_preview").each(function() {
                orderedImages.push($(this).data("img"));
            });
            $("#edit_option_message_images_text").val("," + orderedImages.join(","));
        }
    });
	
	$("#add_option_preview_sortable").sortable({
        cancel: ".nosort",
        update: function() {
            var orderedImages = [];
            $("#add_option_preview_sortable .file_preview").each(function() {
                orderedImages.push($(this).data("img"));
            });
            $("#add_option_message_images_text").val("," + orderedImages.join(","));
        }
    });
	
	
	

	
	
	
	
	
	



    // ✅ السحب والالقاء ✅
    $(document).on("dragover", ".upload-icon", function(e) {
        e.preventDefault();
        e.stopPropagation();
        $(this).addClass("dragover");
    });

    $(document).on("dragleave", ".upload-icon", function(e) {
        e.preventDefault();
        e.stopPropagation();
        $(this).removeClass("dragover");
    });

    $(document).on("drop", ".upload-icon", function(e) {
        e.preventDefault();
        e.stopPropagation();
        $(this).removeClass("dragover");

        let files = e.originalEvent.dataTransfer.files;
        if (!files.length) return;

        let inputId = $(this).attr("for");
        let $input = $("#" + inputId);

        $input.trigger('change', { droppedFiles: files });
    });

});
