<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);
ob_start();
session_start();
if((($_SERVER['SERVER_ADDR']==$_SESSION['demo_server_ip']) && ($_SERVER['REMOTE_ADDR']!=$_SESSION['demo_developer_ip']) && ($_SESSION['id_user']==$_SESSION['demo_user_id'])) || ($_SESSION['sml_si']!=session_id())) {
    die();
}
require_once("../../db/connection.php");
require_once("../functions.php");
$id_image = (int)$_POST['id_image'];
$filename = $_POST['filename'];
$rotate = (int)$_POST['rotate'];
session_write_close();
$ext = explode('.',$filename);
$ext = strtolower(end($ext));
$milliseconds = round(microtime(true) * 1000);
$name = "image_".$milliseconds.".$ext";
$path_image = dirname(__FILE__).'/../../viewer/marker_images/';
if(!file_exists($path_image.'o_'.$filename)) {
    copy($path_image.$filename,$path_image.'o_'.$name);
} else {
    rename($path_image.'o_'.$filename,$path_image.'o_'.$name);
}
$result = $mysqli->query("SELECT rotate FROM sml_images WHERE id=$id_image LIMIT 1;");
if($result) {
    if($result->num_rows==1) {
        $row=$result->fetch_array(MYSQLI_ASSOC);
        $rotate_exist = $row['rotate'];
        $rotate = $rotate_exist + $rotate;
    }
}
if((strtolower($ext)=='jpg') || (strtolower($ext)=='jpeg')) {
    try {
        $src_img = imagecreatefromjpeg($path_image.'o_'.$name);
        imageinterlace($src_img, true);
        $rotate_img = imagerotate($src_img, $rotate, 0);
        imagejpeg($rotate_img, $path_image.$name);
    } catch (Exception $e) {}
} elseif (strtolower($ext)=='png') {
    try {
        $src_img = imagecreatefrompng($path_image.'o_'.$name);
        imageinterlace($src_img, true);
        imagealphablending($src_img, true);
        imagesavealpha($src_img, true);
        $rotate_img = imagerotate($src_img, $rotate, 0);
        imagepng($rotate_img, $path_image.$name);
    } catch (Exception $e) {}
} elseif (strtolower($ext)=='webp') {
    try {
        $src_img = imagecreatefromwebp($path_image.'o_'.$name);
        $rotate_img = imagerotate($src_img, $rotate, 0);
        imagewebp($rotate_img, $path_image.$name);
    } catch (Exception $e) {}
}
$mysqli->query("UPDATE sml_images SET image='$name',rotate=$rotate WHERE id=$id_image;");
require_once("../../services/generate_thumb.php");
ob_end_clean();
echo $name;
exit;