<?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("../../db/connection.php");
require_once("../../backend/functions.php");
$id_map = (int)$_POST['id_map'];
$id_marker = (int)$_POST['id_marker'];
$auth_settings = sml_get_viewer_auth_settings($id_map);
$id_user = ((int)$auth_settings['viewer_auth_mode']>0) ? sml_get_viewer_user_id() : null;
session_write_close();
if(empty($id_user)) {
    echo json_encode(array("status"=>"auth_required"));
    exit;
}
$authorized = false;
$query_check = "SELECT id FROM sml_markers WHERE id=? AND id_map=? AND id_user=? AND to_validate=1 LIMIT 1;";
if($smt_check = $mysqli->prepare($query_check)) {
    $smt_check->bind_param('iii',$id_marker,$id_map,$id_user);
    $smt_check->execute();
    $result_check = get_result($smt_check);
    if(count($result_check)==1) {
        $authorized = true;
    }
}
if(!$authorized) {
    echo json_encode(array("status"=>"auth_required"));
    exit;
}
$queries = array(
    "DELETE FROM sml_markers_categories_assoc WHERE id_marker=?;",
    "DELETE FROM sml_images WHERE id_marker=?;",
    "DELETE FROM sml_reviews WHERE id_marker=?;",
    "DELETE FROM sml_issue_reports WHERE id_marker=?;",
    "DELETE FROM sml_markers WHERE id=? AND id_map=? AND id_user=? AND to_validate=1;"
);
$status = true;
for($i=0;$i<count($queries);$i++) {
    if($smt = $mysqli->prepare($queries[$i])) {
        if($i===4) {
            $smt->bind_param('iii',$id_marker,$id_map,$id_user);
        } else {
            $smt->bind_param('i',$id_marker);
        }
        if(!$smt->execute()) {
            $status = false;
        }
    } else {
        $status = false;
    }
}
echo json_encode(array("status"=>$status ? "ok" : "error"));
