<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);
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("../../db/connection.php");
$id_map = (int)$_POST['id_map'];
$ids = $_POST['ids'];
$id_categories = isset($_POST['categories']) ? $_POST['categories'] : [];
$ids_array = explode(',', $ids);
$ids_array = array_filter(array_map('intval', $ids_array));
if (empty($ids_array)) {
    echo json_encode(array("status"=>"error"));
    exit;
}
$ids_clean = implode(',', $ids_array);
$markers_to_update_date = [];
$incoming_categories_sorted = array_map('intval', $id_categories);
sort($incoming_categories_sorted);
$current_cats_by_marker = [];
$query_c = "SELECT id_marker, id_category FROM sml_markers_categories_assoc WHERE id_marker IN ($ids_clean)";
$result_c = $mysqli->query($query_c);
if($result_c) {
    while($row_c = $result_c->fetch_array(MYSQLI_ASSOC)) {
        $current_cats_by_marker[$row_c['id_marker']][] = (int)$row_c['id_category'];
    }
}
foreach ($ids_array as $id_marker) {
    $existing_categories = isset($current_cats_by_marker[$id_marker]) ? $current_cats_by_marker[$id_marker] : [];
    sort($existing_categories);
    if ($existing_categories !== $incoming_categories_sorted) {
        $markers_to_update_date[] = $id_marker;
    }
}
$query = "DELETE FROM sml_markers_categories_assoc WHERE id_marker IN (SELECT id FROM sml_markers WHERE id IN ($ids_clean) AND id_map=?);";
if($smt = $mysqli->prepare($query)) {
    $smt->bind_param('i',$id_map);
    $smt->execute();
    $smt->close();
}
$values = [];
$types = '';
$params = [];
foreach ($ids_array as $id_marker) {
    foreach ($id_categories as $id_category) {
        $id_category = (int)$id_category;
        $values[] = '(?, ?)';
        $types .= 'ii';
        $params[] = $id_marker;
        $params[] = $id_category;
    }
}
$status_ok = false;
if (!empty($values)) {
    $query = "INSERT INTO sml_markers_categories_assoc (id_marker, id_category) VALUES " . implode(',', $values);
    if ($smt = $mysqli->prepare($query)) {
        $smt->bind_param($types, ...$params);
        $result = $smt->execute();
        $smt->close();
        if($result) {
            $status_ok = true;
        }
    }
} else {
    $status_ok = true;
}
if ($status_ok) {
    if (!empty($markers_to_update_date)) {
        $ids_to_update_str = implode(',', $markers_to_update_date);
        $now = date('Y-m-d H:i:s');
        $mysqli->query("UPDATE sml_markers SET update_date='$now' WHERE id IN ($ids_to_update_str)");
    }
    echo json_encode(array("status"=>"ok"));
} else {
    echo json_encode(array("status"=>"error"));
}