<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);
session_start();
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
    die();
}
require_once("../../backend/functions.php");
require_once("../../db/connection.php");
$settings = get_settings();
if(!empty($settings['timezone'])) {
    date_default_timezone_set($settings['timezone']);
}
$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 = get_result($smt_map);
    if(count($result_map)==1) {
        $row_map = array_shift($result_map);
        $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,'review')) {
    session_write_close();
    echo json_encode(array("status"=>"auth_required"));
    exit;
}
session_write_close();
$name = strip_tags($_POST['name']);
$email = strip_tags($_POST['email']);
$comment = strip_tags($_POST['comment']);
$rating = $_POST['rating'];
$identifier = uniqid('sml');
$now = date('Y-m-d H:i:s');
if(!empty($id_user)) {
    $query_check = "SELECT id FROM sml_reviews WHERE id_marker=? AND id_user=? LIMIT 1;";
    if($smt_check = $mysqli->prepare($query_check)) {
        $smt_check->bind_param('ii',$id_marker,$id_user);
        $smt_check->execute();
        $result_check = get_result($smt_check);
        if(count($result_check)>0) {
            echo json_encode(array("status"=>"duplicate"));
            exit;
        }
    }
}
$query = "INSERT INTO sml_reviews(id_marker,id_user,create_date,name,email,rating,comment,identifier) VALUES(?,?,?,?,?,?,?,?);";
if($smt = $mysqli->prepare($query)) {
    $smt->bind_param('iissssss',$id_marker,$id_user,$now,$name,$email,$rating,$comment,$identifier);
    $result = $smt->execute();
    if($result) {
        sml_send_admin_notification('review',array("id_marker"=>$id_marker,"name"=>$name,"email"=>$email,"rating"=>$rating,"comment"=>$comment));
        echo json_encode(array("status"=>"ok","identifier"=>$identifier));
    } else if($mysqli->errno==1062) {
        echo json_encode(array("status"=>"duplicate"));
    } else {
        echo json_encode(array("status"=>"error"));
    }
}
