<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);
session_start();
ob_start();
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
    die();
}
$marker_images_compression = $_SESSION['marker_images_compression'];
$marker_images_max_size = $_SESSION['marker_images_max_size'];
require_once("../../backend/functions.php");
require_once("../../db/connection.php");
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;
$id_marker = (int)$_POST['id_marker'];
$id_map = 0;
$query_map = "SELECT id_map FROM sml_markers WHERE id=? LIMIT 1;";
if($smt_map = $mysqli->prepare($query_map)) {
    $smt_map->bind_param('i',$id_marker);
    $smt_map->execute();
    $result_map = custom_get_result($smt_map);
    if($row_map = $result_map->fetch_assoc()) {
        $id_map = (int)$row_map['id_map'];
    }
}
$auth_settings = sml_get_viewer_auth_settings($id_map);
$id_user = ((int)$auth_settings['viewer_auth_mode']>0) ? sml_get_viewer_user_id() : null;
if($id_map==0 || !sml_viewer_can_use_feature($id_map,'add_photo')) {
    session_write_close();
    ob_end_clean();
    echo json_encode(array("status"=>"auth_required"));
    exit;
}
session_write_close();
$sender_name = strip_tags($_POST['name']);
$sender_email = strip_tags($_POST['email']);
$map_language = strip_tags($_POST['language']);
if(isset($_FILES) && !empty($_FILES['photo']['name'])){
    $query = "SELECT language,language_domain FROM sml_settings LIMIT 1;";
    $result = $mysqli->query($query);
    if($result) {
        if($result->num_rows==1) {
            $row=$result->fetch_array(MYSQLI_ASSOC);
            if($map_language!='') {
                $language = $map_language;
            } else {
                $language = $row['language'];
            }
            switch($language) {
                case 'pt_BR':
                    $lang_code='pt-BR';
                    break;
                case 'pt_PT':
                    $lang_code='pt-PT';
                    break;
                case 'zh_CN':
                    $lang_code='zh-CN';
                    break;
                case 'zh_TW':
                    $lang_code='zh-TW';
                    break;
                case 'zh_HK':
                    $lang_code='zh-hk';
                    break;
                default:
                    $lang_code = substr($language, 0, 2);
                    break;
            }
            $lang_code_2 = str_replace("_","-",$language);
            if (function_exists('gettext')) {
                if(defined('LC_MESSAGES')) {
                    $result = setlocale(LC_MESSAGES, $language);
                    if(!$result) {
                        setlocale(LC_MESSAGES, $language.'.UTF-8');
                    }
                    if (function_exists('putenv')) {
                        $result = putenv('LC_MESSAGES='.$language);
                        if(!$result) {
                            putenv('LC_MESSAGES='.$language.'.UTF-8');
                        }
                    }
                } else {
                    if (function_exists('putenv')) {
                        $result = putenv('LC_ALL='.$language);
                        if(!$result) {
                            putenv('LC_ALL='.$language.'.UTF-8');
                        }
                    }
                }
                $domain = $row['language_domain'];
                $result = bindtextdomain($domain, "../../locale");
                if(!$result) {
                    $domain = "default";
                    bindtextdomain($domain, "../../locale");
                }
                bind_textdomain_codeset($domain, 'UTF-8');
                textdomain($domain);
            } else {
                if (!function_exists('_')) {
                    function _($a) {
                        return $a;
                    }
                }
            }
        }
    }
    $query_limit = "SELECT marker_images_num FROM sml_maps WHERE id = (SELECT id_map FROM sml_markers WHERE id = ? LIMIT 1) LIMIT 1;";
    if($smt_limit = $mysqli->prepare($query_limit)) {
        $smt_limit->bind_param('i', $id_marker);
        $smt_limit->execute();
        $result_limit = custom_get_result($smt_limit);
        if($row_limit = $result_limit->fetch_assoc()) {
            $marker_images_num = (int)$row_limit['marker_images_num'];
            if($marker_images_num > 0) {
                $query_count = "SELECT COUNT(id) as count_img FROM sml_images WHERE id_marker = ?;";
                if($smt_count = $mysqli->prepare($query_count)) {
                    $smt_count->bind_param('i', $id_marker);
                    $smt_count->execute();
                    $result_count = custom_get_result($smt_count);
                    $row_count = $result_count->fetch_assoc();
                    if((int)$row_count['count_img'] >= $marker_images_num) {
                        ob_end_clean();
                        echo json_encode(array("status"=>"error", "message"=>_("Image limit reached for this marker.")));
                        exit;
                    }
                }
            }
        }
    }
    $allowed_ext = array('jpg','jpeg','png','webp');
    $filename = $_FILES['photo']['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/'.$name;
        $moved = move_uploaded_file($_FILES['photo']['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/thumb/'.$name)) {
                $query = "SELECT (MAX(`priority`)+1) as `priority` FROM sml_images WHERE id_marker=$id_marker;";
                $result = $mysqli->query($query);
                if($result) {
                    $row = $result->fetch_array(MYSQLI_ASSOC);
                    $priority = $row['priority'];
                }
                if(empty($priority)) $priority=0;
                $query = "INSERT INTO sml_images(id_marker, id_user, image, to_validate, sender_name, sender_email, priority) VALUES(?,?,?,1,?,?,?);";
                if($smt = $mysqli->prepare($query)) {
                    $smt->bind_param('iisssi', $id_marker, $id_user, $name, $sender_name, $sender_email, $priority);
                    $result = $smt->execute();
                    if($result) {
                        sml_send_admin_notification('photo',array("id_marker"=>$id_marker,"name"=>$sender_name,"email"=>$sender_email,"photo"=>$name));
                        ob_end_clean();
                        echo json_encode(array("status"=>"ok"));
                    }
                }
            } else {
                ob_end_clean();
                echo json_encode(array("status"=>"error", "message"=>_("Invalid image.")));
            }
        } else {
            ob_end_clean();
            echo json_encode(array("status"=>"error", "message"=>_("Failed to move uploaded file.")));
        }
    } else {
        ob_end_clean();
        echo json_encode(array("status"=>"error", "message"=>_("Only jpg,png,webp files are supported.")));
    }
} else {
    ob_end_clean();
    echo json_encode(array("status"=>"error", "message"=>_("File not provided.")));
}
exit;
?>
