<?php
/**
 * editor_setup.php - কন্টেন্টের মাঝে ইমেজ আপলোড সাপোর্ট এবং TinyMCE কনফিগারেশন
 */

// কন্টেন্টের ছবির জন্য আলাদা ফোল্ডার তৈরি
if (!file_exists('uploads/blog_images')) {
    mkdir('uploads/blog_images', 0777, true);
}

// --- ইমেজ আপলোড হ্যান্ডলার (TinyMCE এর জন্য) ---
if (isset($_GET['action']) && $_GET['action'] == 'upload_content_image') {
    reset($_FILES);
    $temp = current($_FILES);
    if (is_uploaded_file($temp['tmp_name'])) {
        // ফাইল ফরম্যাট ভ্যালিডেশন
        if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])) {
            header("HTTP/1.1 400 Invalid file name.");
            exit;
        }
        if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png", "jpeg", "webp"))) {
            header("HTTP/1.1 400 Invalid extension.");
            exit;
        }

        $file_name = 'img_' . time() . '_' . preg_replace("/[^a-zA-Z0-9.]/", "_", $temp['name']);
        $file_destination = 'uploads/blog_images/' . $file_name;
        
        if (move_uploaded_file($temp['tmp_name'], $file_destination)) {
            echo json_encode(array('location' => $file_destination));
        } else {
            header("HTTP/1.1 500 Server Error");
        }
    } else {
        header("HTTP/1.1 500 Server Error");
    }
    exit;
}
?>

<!-- TinyMCE স্ক্রিপ্ট এবং ইমেজ আপলোড কনফিগারেশন -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/6.7.0/tinymce.min.js"></script>
<script>
tinymce.init({
    selector: '#blog_content',
    plugins: 'image code table lists link media autosave emoticons autoresize',
    toolbar: 'undo redo | formatselect | bold italic | alignleft aligncenter alignright | bullist numlist | link image media | emoticons code',
    height: 400,
    images_upload_url: 'admin.php?view=blogs&action=upload_content_image',
    automatic_uploads: true,
    file_picker_types: 'image',
    images_reuse_filename: true,
    // TinyMCE 6 এর জন্য প্রমিজ ভিত্তিক হ্যান্ডলার
    images_upload_handler: (blobInfo, progress) => new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.withCredentials = false;
        xhr.open('POST', 'admin.php?view=blogs&action=upload_content_image');

        xhr.upload.onprogress = (e) => {
            progress(e.loaded / e.total * 100);
        };

        xhr.onload = () => {
            if (xhr.status < 200 || xhr.status >= 300) {
                reject('HTTP Error: ' + xhr.status);
                return;
            }

            const json = JSON.parse(xhr.responseText);

            if (!json || typeof json.location != 'string') {
                reject('Invalid JSON: ' + xhr.responseText);
                return;
            }

            resolve(json.location);
        };

        xhr.onerror = () => {
            reject('Image upload failed due to a Network Error.');
        };

        const formData = new FormData();
        formData.append('file', blobInfo.blob(), blobInfo.filename());

        xhr.send(formData);
    })
});
</script>