<?php

namespace App\Filters;

use App\Models\Service;
use Illuminate\Http\Request;

class ServiceFilters extends QueryFilters
{
    protected $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
        parent::__construct($request);
    }

    public function search($term)
    {
        $services= Service::search($term)->get();
        $ids=[];
        foreach ($services as $project){
            $ids[]= $project->id;
        }
        $this->builder->whereIn('services.id',$ids);
    }

    public function priceRange($term)
    {
        $split = explode(',', $term);
        if(count($split) == 1)
            return $this->builder->whereBetween('services.basic_tier_price', $split[0])->orWhereBetween('services.standard_tier_price', $split[0])->orWhereBetween('services.pro_tier_price', $split[0]);
        else if(count($split) == 2)
        return $this->builder->whereBetween('services.basic_tier_price', $split)->orWhereBetween('services.standard_tier_price', $split)->orWhereBetween('services.pro_tier_price', $split);
        else return $this->builder;
    }

    public function category($term)
    {
        return $this->builder->where('services.category_id', '=', (int)$term);
    }

    public function skills($term)
    {
        return $this->builder->whereHas('skills', function ($query) use ($term) {
            return $query->whereIn('skills.id', explode(',',$term));
        });
    }

    public function specialities($term)
    {
        return $this->builder->whereHas('categories', function ($query) use ($term) {
            return $query->whereIn('categories.id', explode(',',$term));
        });
    }

    public function sortBy($term, $direction)
    {
        if ($term == 'price') {
            return $this->builder->orderBy('basic_tier_price', $direction);
        } else if ($term == 'date') {
            $this->builder->orderBy('updated_at', $direction);
        } else if ($term = 'rate') {
            return $this->builder->withAvg(
                'rates', 'rate'
            )->orderBy('rates_avg_rate', $direction);
        }
        return $this->builder;
    }

    public function location($term)
    {
        return $this->builder->whereHas('location', function ($query) use ($term) {
            return $query->whereRaw("
                   ST_Distance_Sphere(
                        point(`long`, `lat`),
                        point(?, ?)
                    ) < ?
                ", [
                $term['long'],
                $term['lat'],
                $term['radius'],
            ])->orderByRaw("
                   ST_Distance_Sphere(
                        point(`long`, `lat`),
                        point(?, ?)
                    )
                ", [
                $term['long'],
                $term['lat'],
            ]);
        });
    }
}
