<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Http\Traits\HomeTrait;
use App\Http\Traits\ImageTrait;
use App\Repositries\AuctionRepository;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Astrotomic\Translatable\Translatable;
use Illuminate\Validation\Rule;

class Auction extends Model
{
    use Translatable, ImageTrait, HomeTrait;
    protected $fillable = [
        'image',
        'type',
        'place',
        'status',
        'category_id',
        'country_id',
        'city_id',
        'area_id',
        'date',
        'time',
        'is_home',
        'duration',
        'projects',
        'license_number',
        'entry',
        'opening',
        'lat',
        'long',
        'expire_date',
        'expire_time',
        'price',
        'agency_id',
    ];
    public $translatedAttributes    = ['title', 'description'];
    public $folder                  = 'auctions';

    protected $appends = ['is_favourite', 'map', 'type_text', 'place_text'];

    public static function  rules()
    {
        foreach (LaravelLocalization::getSupportedLanguagesKeys() as $locale) {
            $rules[$locale .  '.title']           = 'required|string|max:255';
            $rules[$locale .  '.description']     = 'required|string';
        }
        $rules['date'] = 'required|date';
        $rules['time'] = 'required';
        $rules['expire_date'] = 'required|date|after_or_equal:date';
        $rules['expire_time'] = 'required';
        $rules['price'] = 'nullable|numeric|min:1';
        $rules['lat']          = ['required', 'regex:/^-?\d{1,2}(\.\d{1,6})?$/'];
        $rules['long'] = ['required', 'regex:/^-?\d{1,3}(\.\d{1,6})?$/'];
        //$rules['type']              = 'required|in:current,past,coming';
        $rules['place']             = 'required|in:online,offline';
        $rules['duration'] = 'required|numeric|min:1';
        $rules['projects'] = 'required|numeric|min:1';
        $rules['entry'] = 'required|numeric|min:1';
        $rules['opening'] = 'required|numeric|min:1';
        $rules['license_number'] = 'required|string|max:255';
        $rules['category_id']       = 'required|exists:categories,id';
        $rules['agency_id']       = 'required|exists:agencies,id';
        $rules['country_id']        = 'required|exists:countries,id';
        $rules['city_id']           = ['required', Rule::exists('cities', 'id')->where('country_id', request()->country_id)];
        $rules['area_id']           =  ['required', Rule::exists('areas', 'id')->where('country_id', request()->country_id)->where('city_id', request()->city_id)];
        $rules['image']             = 'image|mimes:jpg,jpeg,png,gif,svg|max:3072|';
        $rules['is_home'] = 'nullable';
        $rules['images'] = 'nullable|array|min:1|';
        $rules['images.*'] = 'image|mimes:jpg,jpeg,png,gif,svg|max:3072|';
        $rules['gallery'] = 'nullable|array|min:1';
        $rules['gallery.*'] = 'image|mimes:jpg,jpeg,png,gif,svg|max:3072|';
        $rules['features'] =  [Rule::requiredIf(!request()->auction), 'array', 'min:1'];
        $rules['features.*.id'] = 'sometimes';
        $rules['features.*.feature_id'] = 'required|numeric|exists:features,id';
        $rules['features.*.feature_attribute_id'] = 'required|numeric|exists:feature_attributes,id';
        $rules['features.*.value'] = 'required|string|max:255';
        return $rules;
    }

    public function getIsFavouriteAttribute()
    {
        if (auth('client')->check()) {
            return auth('client')->user()->favourites()->where('auction_id', $this->id)->exists();
        }
        return false;
    }

    public function getMapAttribute()
    {
        $auctionRepository = app(AuctionRepository::class);
        if (!auth()->guard('web')->check()) {
            return $auctionRepository->getMap($this);
        }
        return null;
    }

    public function getTypeTextAttribute()
    {
        return __('lang.' . $this->type);
    }

    public function getPlaceTextAttribute()
    {
        return __('lang.' . $this->place);
    }

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function country()
    {
        return $this->belongsTo(Country::class);
    }
    public function city()
    {
        return $this->belongsTo(City::class);
    }
    public function area()
    {
        return $this->belongsTo(Area::class);
    }

    public function images()
    {
        return $this->hasMany(AuctionImage::class);
    }

    public function gallery()
    {
        return $this->hasMany(AuctionGallery::class);
    }

    public function features()
    {
        return $this->hasMany(AuctionFeature::class);
    }

    public function agency()
    {
        return $this->belongsTo(Agency::class);
    }


    public function scopeFilter($query, $filters)
    {
        return $query
            ->when($filters['category_id'] ?? false, function ($query) use ($filters) {
                return $query->where('category_id', $filters['category_id']);
            })
            ->when($filters['agency_id'] ?? false, function ($query) use ($filters) {
                return $query->where('agency_id', $filters['agency_id']);
            })
            ->when($filters['search'] ?? false, function ($query) use ($filters) {
                return $query->where(function ($q) use ($filters) {
                    return $q->whereTranslationLike('title', '%' . $filters['search'] . '%')
                        ->orWhereTranslationLike('description', '%' . $filters['search'] . '%');
                });
            })
            ->when($filters['type'] ?? false, function ($query) use ($filters) {
                return $query->where('type', $filters['type']);
            })
            ->when($filters['place'] ?? false, function ($query) use ($filters) {
                return $query->where('place', $filters['place']);
            })
            ->when($filters['country_id'] ?? false, function ($query) use ($filters) {
                return $query->where('country_id', $filters['country_id']);
            })
            ->when($filters['city_id'] ?? false, function ($query) use ($filters) {
                return $query->where('city_id', $filters['city_id']);
            })
            ->when($filters['area_id'] ?? false, function ($query) use ($filters) {
                return $query->where('area_id', $filters['area_id']);
            })
            ->when($filters['date'] ?? false, function ($query) use ($filters) {
                return $query->whereDate('date', $filters['date']);
            })
            ->when($filters['date_from'] ?? false, function ($query) use ($filters) {
                return $query->whereDate('date', '>=', $filters['date_from']);
            })
            ->when($filters['date_to'] ?? false, function ($query) use ($filters) {
                return $query->whereDate('date', '<=', $filters['date_to']);
            })
            ->when($filters['price_from'] ?? false, function ($query) use ($filters) {
                return $query->whereDate('price', '>=', $filters['price_from']);
            })
            ->when($filters['price_to'] ?? false, function ($query) use ($filters) {
                return $query->whereDate('price', '<=', $filters['price_to']);
            })
            ->when($filters['expire_date_to'] ?? false, function ($query) use ($filters) {
                return $query->whereDate('expire_date', '<=', $filters['expire_date_to']);
            })
            ->when($filters['except_id'] ?? false, function ($query) use ($filters) {
                return $query->where('id', '!=', $filters['except_id']);
            })
            ->when($filters['is_home'] ?? false, function ($query) {
                return $query->home();
            });
    }

    public function scopeExpired($query)
    {
        return $query->whereNot('type', 'past')->whereRaw("CONCAT(expire_date, ' ', expire_time) <= ?", [now()]);
    }

    public function scopeStart($query)
    {
        return $query->where('type', 'coming')->whereRaw("CONCAT(date, ' ', time) <= ?", [now()]);
    }
}
