<?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");
require('../vendor/autoload.php');
session_write_close();
use proj4php\Proj4php;
use proj4php\Point;
use proj4php\Proj;
$id_map = (int)$_POST['id_map'];
$language = strip_tags($_POST['language']);
$settings = get_settings();
$extent = "";
$array_story_lang = array();
$array_markers_lang = array();
$query = "SELECT extent,languages_enabled,language as language_map FROM sml_maps WHERE id=$id_map LIMIT 1;";
$result = $mysqli->query($query);
if($result) {
    if ($result->num_rows == 1) {
        $row = $result->fetch_array(MYSQLI_ASSOC);
        $extent = $row['extent'];
        $extent = json_decode($extent, true);
        $count_languages_enabled = 0;
        if(empty($row['languages_enabled'])) {
            $row['languages_enabled']=array();
        } else {
            $row['languages_enabled']=json_decode($row['languages_enabled'],true);
        }
        foreach ($row['languages_enabled'] as $lang_enabled) {
            if($lang_enabled==1) {
                $count_languages_enabled++;
            }
        }
        $map_language = $row['language_map'];
        $default_language_settings = $settings['language'];
        if(empty($map_language)) $map_language=$default_language_settings;
        if($count_languages_enabled>=1) {
            if(!empty($language) && $language!=$map_language) {
                $query_lang = "SELECT * FROM sml_story_lang WHERE language='$language' AND id_story IN (SELECT id FROM sml_story WHERE id_map=$id_map);";
                $result_lang = $mysqli->query($query_lang);
                if($result_lang) {
                    if ($result_lang->num_rows > 0) {
                        while($row_lang = $result_lang->fetch_array(MYSQLI_ASSOC)) {
                            $id_story = $row_lang['id_story'];
                            unset($row_lang['id_story']);
                            unset($row_lang['language']);
                            $array_story_lang[$id_story]=$row_lang;
                        }
                    }
                }
                $query_lang = "SELECT * FROM sml_markers_lang WHERE language='$language' AND id_marker IN (SELECT id_marker FROM sml_story WHERE id_map=$id_map);";
                $result_lang = $mysqli->query($query_lang);
                if($result_lang) {
                    if ($result_lang->num_rows > 0) {
                        while($row_lang = $result_lang->fetch_array(MYSQLI_ASSOC)) {
                            $id_marker = $row_lang['id_marker'];
                            unset($row_lang['id_marker']);
                            unset($row_lang['language']);
                            $array_markers_lang[$id_marker]=$row_lang;
                        }
                    }
                }
            }
        }
    }
}
$array_story = array();
$query = "SELECT s.id as id_story,s.id_marker,m.lat,m.lon,m.name,m.description,s.zoom,s.description as description_story,GROUP_CONCAT(i.image) as images,s.priority FROM sml_story as s
JOIN sml_markers as m on s.id_marker = m.id
LEFT JOIN sml_images as i on m.id = i.id_marker AND i.main=1
WHERE s.id_map=?
GROUP BY s.id_marker, m.lat, m.lon, m.name, m.description, s.zoom, s.description, s.priority
ORDER BY s.priority ASC;";
if($smt = $mysqli->prepare($query)) {
    $smt->bind_param('i',$id_map);
    $result = $smt->execute();
    if($result) {
        $result = get_result($smt);
        $count = count($result);
        if($count>0) {
            while($row = array_shift($result)) {
                $id_marker = $row['id_marker'];
                $id_story = $row['id_story'];
                if(array_key_exists($id_marker,$array_markers_lang)) {
                    if (!empty($row['description']) && !empty($array_markers_lang[$id_marker]['description'])) {
                        $row['description'] = $array_markers_lang[$id_marker]['description'];
                    }
                }
                if(array_key_exists($id_story,$array_story_lang)) {
                    if (!empty($row['description_story']) && !empty($array_story_lang[$id_story]['description'])) {
                        $row['description_story'] = $array_story_lang[$id_story]['description'];
                    }
                }
                $row['lat'] = str_replace(",",".",$row['lat']);
                $row['lon'] = str_replace(",",".",$row['lon']);
                if(!isValidCoordinate($row['lat'],$row['lon'])) {
                    continue;
                }
                if(!empty($extent)) {
                    if(!isCoordinateInsideExtent($row['lat'],$row['lon'],$extent)) {
                        continue;
                    }
                }
                if(!empty($row['description_story'])) $row['description']=$row['description_story'];
                unset($row['description_story']);
                if(empty($row['images'])) $row['images']='';
                $array_story[] = $row;
            }
        }
    }
}
ob_end_clean();
echo json_encode(array("story"=>$array_story));

function isValidCoordinate($latitude, $longitude) {
    if (!is_numeric($latitude) || $latitude < -90 || $latitude > 90) {
        return false;
    }
    if (!is_numeric($longitude) || $longitude < -180 || $longitude > 180) {
        return false;
    }
    return true;
}
function isCoordinateInsideExtent($latitude, $longitude, $extent) {
    $proj4 = new Proj4php();
    $projWGS84 = new Proj('EPSG:4326', $proj4);
    $proj3857 = new Proj('EPSG:3857', $proj4);
    $point = new Point($longitude, $latitude, $projWGS84);
    $point3857 = $proj4->transform($proj3857, $point);
    return (
        $point3857->x >= $extent[0] &&
        $point3857->x <= $extent[2] &&
        $point3857->y >= $extent[1] &&
        $point3857->y <= $extent[3]
    );
}