<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Library\GeoLib;
use App\Models\Municipality;
use App\Models\Area;

class AreaController extends Controller
{
    public function getAreas($latlng) {
        list($lat, $lng) = explode(',', $latlng);

        $municipality = $this->getMunicipalityFromLatLng($lat, $lng);
        // dd($municipality);

        try {
            $areas = Area::where('comune_id', $municipality->id)->get();
        } catch (\ErrorException $e) {
            return null;
        }

        return $this->buildPolygons($areas);
    }

    private function getMunicipalityFromLatLng($lat, $lng) {
        $municipalityRaw = GeoLib::getMunicipalityFromCoords($lat, $lng);
        $municipality = Municipality::where('nome', $municipalityRaw)->first();
        
        return $municipality;
    }

    private function buildPolygons($areas) {
        $polygons = [
            'type'      => 'FeatureCollection',
            'features'  => [],
        ];

        foreach ($areas as $area) {
            $feature = [
                'type'          => 'Feature',
                'properties'    => [
                    'area_id'       => $area->id,
                    'area_color'    => $area->colore,
                ],
                'geometry'      => [
                    'type'          => 'Polygon',
                    'coordinates'   => [
                        json_decode($area->vertici),
                    ],
                ],
            ];
            array_push($polygons['features'], $feature);
        }

        return json_encode($polygons);
    }
}
