<?php
header('Content-Type: application/json');

// Upload folder
$targetDir = __DIR__ . '/uploads/ckeditor/';
if (!is_dir($targetDir)) mkdir($targetDir, 0777, true);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['upload'])) {

    $file = $_FILES['upload'];

    // Sanitize filename
    $filename = time() . '_' . preg_replace('/[^a-zA-Z0-9_\.-]/', '_', $file['name']);
    $targetFile = $targetDir . $filename;

    $tmp = $file['tmp_name'];

    $info = getimagesize($tmp);
    if(!$info){
        echo json_encode([
            "uploaded" => 0,
            "error" => ["message" => "Invalid image file."]
        ]);
        exit;
    }

    // Compress only (no resize)
    if($info['mime'] == 'image/jpeg'){
        $img = imagecreatefromjpeg($tmp);
        imagejpeg($img, $targetFile, 60); // 70% quality
        imagedestroy($img);
    }
    elseif($info['mime'] == 'image/png'){
        $img = imagecreatefrompng($tmp);
        imagepng($img, $targetFile, 7); // PNG compression
        imagedestroy($img);
    }
    else{
        // fallback (non image)
        move_uploaded_file($tmp, $targetFile);
    }

    $baseUrl = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'];
    $url = $baseUrl . '/Krb-demo-2/admin/uploads/ckeditor/' . $filename;

    echo json_encode([
        "uploaded" => 1,
        "fileName" => $filename,
        "url" => $url
    ]);

} else {
    echo json_encode([
        "uploaded" => 0,
        "error" => ["message" => "No file uploaded or invalid request."]
    ]);
}
