<?php

namespace App\Filters;

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

class ProjectFilters extends QueryFilters
{
    protected $request;

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

    public function search($term)
    {

        $projects = Project::search($term)->get();


        $ids = [];
        foreach ($projects as $project) {
            $ids[] = $project->id;
        }
        $this->builder->whereIn('projects.id', $ids);
    }

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

    public function category($term)
    {
        return $this->builder->whereIn('projects.category_id', explode(',', $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 pricingType($term)
    {
        str_replace('Fixed','Fixed Price', $term);
        return $this->builder->whereIn('projects.budget_type', explode(',', $term));
    }

    public function sortBy($term, $direction)
    {
        if ($term == 'price') {
            return $this->builder->orderBy('amount', $direction);
        } else if ($term == 'date') {
            $this->builder->orderBy('updated_at', $direction);
        }
        $this->builder->where('projects.is_public', 1);
        return $this->builder->where('projects.status', '!=', 'Drafted');
    }

    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'],
            ]);
        });
    }
}
