<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once 'db_manager.php';

use function Catcher\recovery;

function gen_geojson($name, $features) {
    return (object)[
        "type" => "FeatureCollection",
        "name" => $name,
            "crs" => (object) [
                "type" => "name",
                "properties" => (object) [
                    "name" => "urn:ogc:def:crs:OGC:1.3:CRS84"
                ]
            ],
        "features" => $features
    ];
}
function gen_feature($settlement) {
    $settlement = (object) $settlement;
    $settlement->info_exist = ($settlement->info_exist == 1)? true : false;
    if($settlement->slider)
        $settlement->slider = json_decode($settlement->slider);
    if($settlement->images)
        $settlement->images = json_decode($settlement->images);
    $latitude = $settlement->latitude;
    $longitude = $settlement->longitude;
    unset($settlement->latitude);
    unset($settlement->longitude);

    return (object) [
        "type" => "Feature",
        "properties" => $settlement,
        "geometry" => (object) [
            "type" => "Point",
            "coordinates" => [$longitude, $latitude]
        ]
    ];
}
function gen_json($obj) :string {
    return json_encode($obj, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}

$body_raw = file_get_contents('php://input');
$body = json_decode($body_raw);

$mode = $body->mode;

$result = (object)[];

switch($mode) {
    case 'geojsons':
        $periods_geojson = (object) [];
        $settlements = $db_manager->select_all();
        foreach($settlements as $settlement) {
            $period = ((object)$settlement)->period;
            if(empty($periods_geojson->$period))
                $periods_geojson->$period = [];
            array_push($periods_geojson->$period, gen_feature($settlement));
        };

        foreach($periods_geojson as $name=>$features) {
            $result->$name = gen_geojson($name, $features);
        }
        
        echo gen_json($result);
        break;
    case 'file':
        $full_path = $body->path;

        if (is_file($full_path)) {
            // Определяем MIME-тип (например, для видео/mp4, изображений и т.д.)
            $mime_type = mime_content_type($full_path);

            // Устанавливаем заголовки
            header('Content-Type: ' . $mime_type);
            header('Content-Length: ' . filesize($full_path));

            // Отдаём файл
            readfile($full_path);
            exit();
        } else {
            http_response_code(404);
            echo json_encode(['error' => 'File not found']);
        }
        break;

    default: 
        header('Content-Type: application/json');
        echo gen_json((object)['msg' => "Не передан mode"]);
        break;
}
?>