<?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())) {
    //DEMO CHECK
    die();
}
require_once(dirname(__FILE__).'/../functions.php');
require_once(dirname(__FILE__).'/ImageResizeException.php');
require_once(dirname(__FILE__).'/ImageResize.php');
use \Gumlet\ImageResize;
$settings = get_settings();
$user_info = get_user_info($_SESSION['id_user']);
if(!empty($user_info['language'])) {
    set_language($user_info['language'],$settings['language_domain']);
} else {
    set_language($settings['language'],$settings['language_domain']);
}
if (!file_exists(dirname(__FILE__).'/../../viewer/marker_images/')) {
    mkdir(dirname(__FILE__).'/../../viewer/marker_images/', 0775);
}
$marker_images_compression = $_SESSION['marker_images_compression'];
$marker_images_max_size = $_SESSION['marker_images_max_size'];
session_write_close();
if($marker_images_compression=="") $marker_images_compression=90;
if($marker_images_max_size=="") $marker_images_max_size=0;
$response = [
    'success' => false,
    'filename' => '',
    'gps' => null
];
if(isset($_FILES) && !empty($_FILES['file']['name'])){
    $allowed_ext = array('jpg','jpeg','png','webp','mp4','wov','webm');
    $filename = $_FILES['file']['name'];
    $ext = explode('.',$filename);
    $ext = strtolower(end($ext));
    $milliseconds = round(microtime(true) * 1000);
    if(in_array($ext,$allowed_ext)){
        $is_image = true;
        switch($ext){
            case 'mp4':
            case 'mov':
            case 'webm':
                $is_image = false;
                $name = "video_".$milliseconds.".$ext";
                break;
            default:
                $name = "image_".$milliseconds.".$ext";
                break;
        }
        $path_dest = dirname(__FILE__).'/../../viewer/marker_images/'.$name;
        $moved = move_uploaded_file($_FILES['file']['tmp_name'],$path_dest);
        if($moved) {
            $response['success'] = true;
            $response['filename'] = $name;
            if($is_image) {
                $lat = 0;
                $lon = 0;
                if(function_exists('exif_read_data')) {
                    $exif = @exif_read_data($path_dest);
                    if ((isset($exif["GPSLatitude"])) && (isset($exif["GPSLongitude"]))) {
                        $latitude = gps($exif["GPSLatitude"], $exif['GPSLatitudeRef']);
                        $longitude = gps($exif["GPSLongitude"], $exif['GPSLongitudeRef']);
                        if ($latitude != 0 && !empty($latitude) && !is_nan($latitude)) {
                            if(is_valid_latitude($latitude)) {
                                $lat = $latitude;
                            }
                        }
                        if ($longitude != 0 && !empty($longitude) && !is_nan($longitude)) {
                            if(is_valid_longitude($longitude)) {
                                $lon = $longitude;
                            }
                        }
                    }
                    if($lat!==0 && $lon!==0) {
                        $response['gps'] = ['lat' => $lat, 'lon' => $lon];
                    }
                }
                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);
                }
            }
            include("../../services/generate_thumb.php");
        }
    }
}
ob_end_clean();
echo json_encode($response);
exit;

function gps($coordinate, $hemisphere) {
    if (is_string($coordinate)) {
        $coordinate = array_map("trim", explode(",", $coordinate));
    }
    for ($i = 0; $i < 3; $i++) {
        $part = explode('/', $coordinate[$i]);
        if (count($part) == 1) {
            $coordinate[$i] = $part[0];
        } else if (count($part) == 2) {
            if($part[1]!=0) {
                $coordinate[$i] = floatval($part[0])/floatval($part[1]);
            } else {
                $coordinate[$i] = 0;
            }
        } else {
            $coordinate[$i] = 0;
        }
    }
    list($degrees, $minutes, $seconds) = $coordinate;
    $sign = ($hemisphere == 'W' || $hemisphere == 'S') ? -1 : 1;
    return $sign * ($degrees + $minutes/60 + $seconds/3600);
}

function is_valid_latitude($latitude) {
    return is_numeric($latitude) && $latitude >= -90 && $latitude <= 90;
}

function is_valid_longitude($longitude) {
    return is_numeric($longitude) && $longitude >= -180 && $longitude <= 180;
}