<?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;

$period_view = (object) [
    'rArcheology' => '16 век и ранее',
    'r1675' => '17 век',
    'r1740' => '18 век',
    'r1781' => '19 век',
    'r1858' => '1901-1920',
    'r1900' => '1921-1940',
    'r1926' => '1941-1960',
    'r1936' => '1961-1980',
    'r1946' => '1981-2000',
    'r200-now' => '2000 и н.в.'
];

$get_fs = null;
$get_fs = recovery(function (string $path) use (&$get_fs) {
    $result = (object) ['files' => (object)[]];

    $dirs = array_filter(scandir($path), function ($dir) {
        return $dir !== '.' &&  $dir !== '..';
    });

    foreach($dirs as $dir) {
        $new_path = $path . DIRECTORY_SEPARATOR . $dir;
        if(is_dir($new_path)) 
            $result->$dir = $get_fs($new_path);
        else if(is_file($new_path)) {
            $filename = pathinfo($new_path, PATHINFO_FILENAME);
            $result->files->$filename = $new_path;
        } 
    }

    return $result;
}, function($e) {
    throw $e; 
});

$main = recovery(function (object $period_view) use (&$get_fs,&$db_manager)
{
    $db_manager->delete_table();
    $db_manager->create_table();

    $fs = $get_fs('.' . DIRECTORY_SEPARATOR . 'data');

    $removeLeadingDot = function(?string $path): ?string {
        if ($path === null) return null;
        return preg_replace('#^\.(?=[/\\\\])#', '', $path);
    };


    $removeLeadingDotFromJsonArray = function(?string $json): ?string {
        if ($json === null) return null;
        $arr = json_decode($json);
        if (!is_array($arr)) return $json;
        $arr = array_map(fn($p) => preg_replace('#^\.(?=.*)#', '', $p), $arr);
        return json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    };


    $settlements_data = [];

    $material_path = $fs->material;
    foreach ($fs->geojson->files as $geojson_path) {
        if (!file_exists($geojson_path)) {
            echo 'Невалидный geojson-path : ' . $geojson_path;
            continue;
        }
        
        $geojson = json_decode(file_get_contents($geojson_path));
        $features = $geojson->features;
        $basename = pathinfo($geojson_path, PATHINFO_FILENAME);
        $period = $period_view->$basename;

        foreach($features as $feature) {
            $properties = $feature->properties;
            $coordinates = $feature->geometry->coordinates;

            $en = $properties->en;
            
            $info_exist = 0;

            $background = null;
            $images = null;
            $slider = null;
            $video = null;

            if(!empty($en) && isset($material_path->$en)) {
                $material = $material_path->$en;

                $tmp = array_values((array)$material->background->files);
                $background = end($tmp);

                if (!empty($material->image) && isset($material->image)) {
                    $tmp = array_values((array)$material->image->files);
                    $images = json_encode($tmp, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?: null;
                }

                if (!empty($material->slider) && isset($material->slider)) {
                    $tmp = array_values((array)$material->slider->files);
                    $slider = json_encode($tmp, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?: null;
                }

                if (!empty($material->video) && isset($material->video)) {
                    $tmp = array_values((array)$material->video->files);
                    $video = end($tmp);
                }

                $info_exist = 1;
            }

            switch (mb_strtolower($properties->Tupe)) {
                case 'археология':
                    $type = 'археообъект';
                    break;
                case 'юрты':
                    $type = 'юрта';
                    break;
                default:
                    $type = $properties->Tupe;
            }

            // Убираем точку в путях перед записью в массив
            $background = $removeLeadingDot($background);
            $images = $removeLeadingDotFromJsonArray($images);
            $slider = $removeLeadingDotFromJsonArray($slider);
            $video = $removeLeadingDot($video);

            array_push($settlements_data, [
                'name' => $properties->Name,
                'type' => $type,
                'period' => $period, 
                'longitude' => $coordinates[0],
                'latitude' => $coordinates[1],
                'info_exist' => $info_exist,
                'slider' => $slider,
                'images' => $images,
                'video' => $video,
                'background' => $background
            ]);
        }
    }

    $settlements_arg = array_map(
        fn($settlements) => array_values((array) $settlements), 
        $settlements_data
    );

    $db_manager->create_all($settlements_arg);
}, function($e) {
    throw $e;
});

$main($period_view);
?>