<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);
session_start();
ob_start();
$marker_images_compression = $_SESSION['marker_images_compression'];
$marker_images_max_size = $_SESSION['marker_images_max_size'];
session_write_close();
if (!file_exists(dirname(__FILE__).'/../marker_images_tmp/')) {
    mkdir(dirname(__FILE__).'/../marker_images_tmp', 0775);
}
require_once(dirname(__FILE__).'/ImageResizeException.php');
require_once(dirname(__FILE__).'/ImageResize.php');
use \Gumlet\ImageResize;
if($marker_images_compression=="") $marker_images_compression=90;
if($marker_images_max_size=="") $marker_images_max_size=0;
if(isset($_FILES) && !empty($_FILES['file']['name'])){
    $allowed_ext = array('jpg','jpeg','png','webp');
    $filename = $_FILES['file']['name'];
    $ext = explode('.',$filename);
    $ext = strtolower(end($ext));
    if(in_array($ext,$allowed_ext)){
        $milliseconds = round(microtime(true) * 1000);
        $name = "image_".$milliseconds.".$ext";
        $path_dest = dirname(__FILE__).'/../marker_images_tmp/'.$name;
        $moved = move_uploaded_file($_FILES['file']['tmp_name'],$path_dest);
        if($moved) {
            if($marker_images_compression<100 || $marker_images_max_size>0) {
                $image = new ImageResize($path_dest);
                $image->quality_jpg = $marker_images_compression;
                $image->gamma(false);
                if($marker_images_max_size>0) {
                    $image->resizeToLongSide(3840);
                }
                $image->save($path_dest);
            }
            if((strtolower($ext)=='jpg') || (strtolower($ext)=='jpeg')) {
                try {
                    $src_img = imagecreatefromjpeg($path_dest);
                    imageinterlace($src_img, true);
                    imagejpeg($src_img, $path_dest);
                } catch (Exception $e) {}
            } elseif (strtolower($ext)=='png') {
                try {
                    $src_img = imagecreatefrompng($path_dest);
                    imageinterlace($src_img, true);
                    imagealphablending($src_img, true);
                    imagesavealpha($src_img, true);
                    imagepng($src_img, $path_dest);
                } catch (Exception $e) {}
            }
            ob_end_clean();
            include("../../services/generate_thumb.php");
            if(file_exists(dirname(__FILE__).'/../marker_images_tmp/thumb/'.$name)) {
                ob_end_clean();
                echo $name;
            } else {
                ob_end_clean();
                echo 'ERROR: '._("Invalid image.");
            }
        } else {
            ob_end_clean();
            echo 'ERROR: code:'.$_FILES["file"]["error"];
        }
    }else{
        ob_end_clean();
        echo 'ERROR: '._("Only jpg,png,webp files are supported.");
    }
}else{
    ob_end_clean();
    echo 'ERROR: '._("File not provided.");
}
exit;
