<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Property;
use App\Models\Epigraph;
use App\Http\Requests\Api\FilterData;
use MatanYadaev\EloquentSpatial\Objects\Point;

class FilterController extends Controller
{
    public function get(FilterData $request)
    {
        $data = $request->validated();
        //$themes = $data && array_key_exists('themes', $data) ? $data['themes'] : [];
        $themes = [];
        $subThemes = $data && array_key_exists('sub_themes', $data) ? $data['sub_themes'] : [];
        $typologies = $data && array_key_exists('typologies', $data) ? $data['typologies'] : [];
        $subTypologies = $data && array_key_exists('sub_typologies', $data) ? $data['sub_typologies'] : [];
        $locations = $data && array_key_exists('locations', $data) ? $data['locations'] : [];
        $lat = $data && array_key_exists('lat', $data) ? $data['lat'] : null;
        $lng = $data && array_key_exists('lng', $data) ? $data['lng'] : null;
        $radius = $data && array_key_exists('radius', $data) ? $data['radius'] : null;
        $propertiesQuery = Property::full()
            ->select('*')
            ->with([
                'typologies' => function ($query) {
                    $query->full();
                },
                'themes' => function ($query) {
                    $query->full();
                },
                'accesses' => function ($query) {
                    $query->full()->accessFilters();
                },
                'images' => function ($query) {
                    $query->full()->orderBy('id', 'asc')->with('image');
                }
            ]);
        $epigraphsQuery = Epigraph::full()
                ->select('*')
                ->with([
                    'themes' => function ($query) {
                        $query->full();
                    },
                    'location' => function ($query) {
                        $query->full();
                    },
                    'images' => function ($query) {
                        $query->full();
                    }
                ]);
        if (count($themes) > 0) {
            $propertiesQuery->whereHas('themes', function ($query) use ($themes) {
                $query->whereIn('theme_id', $themes);
            });
        }
        if (count($subThemes) > 0) {
            $propertiesQuery->whereHas('themes', function ($query) use ($subThemes) {
                $query->whereIn('theme_id', $subThemes);
            });
            $epigraphsQuery->whereHas('themes', function ($query) use ($subThemes) {
                $query->whereIn('theme_id', $subThemes);
            });
        }
        if (count($typologies) > 0) {
            $propertiesQuery->whereHas('typologies', function ($query) use ($typologies) {
                $query->whereIn('typology_id', $typologies);
            });
            $epigraphsQuery->whereRaw('1 = 0');
        }
        if (count($subTypologies) > 0) {
            $propertiesQuery->whereHas('typologies', function ($query) use ($subTypologies) {
                $query->whereIn('typology_id', $subTypologies);
            });
            $epigraphsQuery->whereRaw('1 = 0');
        }
        if (count($locations) > 0) {
            $propertiesQuery->whereIn('local_id', $locations);
            $epigraphsQuery->whereIn('local_id', $locations);
        }
        if (!is_null($lat) && !is_null($lng) && !is_null($radius)) {
            $propertiesQuery->distanceSphere(
                'geolocation',
                new Point($lat, $lng),
                $radius
            );

            $epigraphsQuery->whereRaw('1 = 0');
        }
        $properties = $propertiesQuery->get();
        $epigraphs = $epigraphsQuery->get();
        $cleanProperties = $this->formatProperties($properties);
        $cleanEpigraphs = $this->formatEpigraphs($epigraphs);
        $returnData = array_merge($cleanProperties, $cleanEpigraphs);
        return response()->json($returnData);
    }

    private function formatProperties($properties)
    {
        $cleanProperties = [];
        foreach ($properties as $property) {
            $imageLegend = $property->images->first();
            if (!is_null($imageLegend) && !is_null($imageLegend->image)) {
                $image = getImage($imageLegend->image, '260x170');
            } else {
                $image = (object)[
                    "url" => null,
                    "alt" => null
                ];
            }
            $cleanProperties[] = [
                "id"           => $property->id,
                "title"        => $property->title,
                "slug"         => $property->lang_slug,
                "image"        => $image,
                "address"      => $property->searchable_address,
                "isAccessible" => $property->accesses->count() > 0,
                "local"        => $property->location ? $property->location->title : "",
                "type"         => "property",
            ];
        }
        return $cleanProperties;
    }
    private function formatEpigraphs($epigraphs)
    {
        $cleanEpigraphs = [];
        foreach ($epigraphs as $epigraph) {
            if (count($epigraph->properties) > 0) {
                $imageLegend = $epigraph->images->first();
                if (!is_null($imageLegend) && !is_null($imageLegend->image)) {
                    $image = getImage($imageLegend->image, '260x170');
                } else {
                    $image = null;
                }
            } else {
                $image = null;
            }
            $out = [
                "id"           => $epigraph->id,
                "title"        => $epigraph->epigraph_title,
                "slug"         => $epigraph->lang_slug,
                "isAccessible" => false,
                "image"        => $image,
                "address"      => $epigraph->present_location,
                "properties"   => $epigraph->properties->pluck("id")->toArray(),
                "local"        => $epigraph->location ? $epigraph->location->title : "",
                "type"         => "epigraph",
            ];
            if (!is_null($image)) {
                $out['image'] = $image;
            }
            $cleanEpigraphs[] = $out;
        }
        return $cleanEpigraphs;
    }
}
