<?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();
}
require_once("../../backend/functions.php");
require_once("../../db/connection.php");
session_write_close();
$id_map = (int)$_POST['id_map'];
$query = "SELECT add_markers_countries_allowed FROM sml_maps WHERE id=$id_map LIMIT 1;";
$result = $mysqli->query($query);
$add_markers_countries_allowed = [];
if($result) {
    if ($result->num_rows == 1) {
        $row = $result->fetch_array(MYSQLI_ASSOC);
        $add_markers_countries_allowed = $row['add_markers_countries_allowed'];
    }
}
$add_markers_countries_allowed = json_decode($add_markers_countries_allowed, true);
if (!is_array($add_markers_countries_allowed) || empty($add_markers_countries_allowed)) {
    ob_end_clean();
    echo json_encode([
        "type" => "FeatureCollection",
        "features" => []
    ]);
    exit;
}
$file_path = '../countries/countries.geojson';
if (!file_exists($file_path)) {
    ob_end_clean();
    echo json_encode(["error" => "countries.geojson does not exist"]);
    exit;
}
$file_content = file_get_contents($file_path);
$geojson_data = json_decode($file_content, true);
$features_filtered = [];
foreach ($geojson_data['features'] as $feature) {
    if (isset($feature['properties']['name'])) {
        $country_name = $feature['properties']['name'];
        if (in_array($country_name, $add_markers_countries_allowed)) {
            $features_filtered[] = $feature;
        }
    }
}
$geojson = [
    "type" => "FeatureCollection",
    "crs" => [
        "type" => "name",
        "properties" => [ "name" => "urn:ogc:def:crs:OGC:1.3:CRS84" ]
    ],
    "features" => $features_filtered
];
ob_end_clean();
echo json_encode($geojson);