<?php

namespace App\Services;

use App\Models\Location;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use App\Exceptions\ApiHttpException;
use App\Libs\Api\ParsedListParams;
use Illuminate\Database\Eloquent\Builder;
use App\Services\DataService;
use Illuminate\Support\Carbon;

class LocationDataService extends DataService
{
    /**
     * Gets and filters locations
     *
     * @param ParsedListParams $params - Filter and order data
     * @return Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function list(ParsedListParams $params): LengthAwarePaginator
    {
        /** @var Builder $query */
        $query = Location::full()
            ->with([
                'image',
                'tags' => function ($query) {
                    $query->full();
                },
            ])
            ->withCount([
                'exhibitions' => function ($exhibitsQ) {
                    $exhibitsQ->whereDate('date_from', '<=', now());
                    $exhibitsQ->whereDate('date_to', '>=', now());
                }
            ]);
        //check if the default filters are to be applied
        $this->applyDefaultFilters($query, $params);
        $this->applyQueryParams($query, $params);
        return $query->paginate($params->itemsPerPage, ['*'], 'page', $params->pageNumber);
    }


    /**
     * Finds a single model for the Location
     *
     * @param int $id
     * @throws ApiHttpException if the provided Location record is not found.
     * @return Location
     */
    public function find(int $id): Location
    {
        $location = Location::full()
            ->where('status', 'published')
            ->with([
                'tags' => function ($query) {
                    $query->full();
                },
                'exhibitions' => function ($exhibitsQ) {
                    $exhibitsQ->full()->with(
                        [
                            'image',
                            'artists' => function ($artistsQ) {
                                $artistsQ->full()->with('image')->select('*');
                            }
                        ]
                    );
                    $exhibitsQ->whereDate('date_from', '<=', now());
                    $exhibitsQ->whereDate('date_to', '>=', now());
                },
                'image',
            ])->where('id', $id)->first();

        if (!$location) {
            throw new ApiHttpException(404, 'item_not_found');
        }

        return $location;
    }


    /**
     * applyQueryParams
     *
     * @param Builder &$query
     * @param ParsedListParams $params
     * @return void
     */
    private function applyQueryParams(Builder $query, ParsedListParams $params): void
    {

        $orderDirection = $params->orderDirection;
        $orderBy        = $params->orderBy;
        if ($orderBy === 'name') {
            $orderBy = 'title';
        }
        $query->orderBy($orderBy, $orderDirection);

        // Apply the specific Filters
        // Location name Filter
        if (isset($params->filters['name'])) {
            $query->where('title', 'like', $params->filters['name'] . '%');
        }


        // Tag id Filter
        if (isset($params->filters['tag_id'])) {
            $query->whereHas('tags', function ($tagQ) use ($params) {
                $tagQ->where('id', $params->filters['tag_id']);
            });
        }

        // Tag type Filter
        if (isset($params->filters['tag_type'])) {
            $query->whereHas('tags', function ($tagQ) use ($params) {
                $tagQ->where('type', $params->filters['tag_type']);
            });
        }

        // Coordinates filter
        $this->applyLocationFilters($query, $params);
    }
}
