<?php

namespace App\Models;

use App\Models\Backoffice\MediaItem;
use App\Models\Backoffice\Support\ContentTypeModel;
use App\Models\Backoffice\Traits\LanguageSupportTrait;

use function Laravel\Prompts\table;

class Competition extends ContentTypeModel
{
    use LanguageSupportTrait;

    protected $hidden = ['languages', "websites"];
    protected $with = ['languages', "websites"];
    protected $casts = [
        'publication_date' => 'date',
        'submission_until' => 'datetime',
        'information_request_until' => 'datetime',
        'application_deadline' => 'datetime',
        'deadline' => 'datetime',
        'plans_deadline' => 'datetime',
        'model_deadline' => 'datetime',
        'jury_date' => 'datetime',
        'announcement_date' => 'datetime',
        'registration_deadline' => 'datetime',
        'is_competition' => 'bool',
        'is_public' => 'bool',
    ];

    public function promoterCountry()
    {
        return $this->belongsTo(Country::class);
    }

    public function locationCountry()
    {
        return $this->belongsTo(Country::class);
    }

    public function procedureTypes()
    {
        return $this->belongsToMany(ProcedureType::class, 'competition_procedure_types')
            ->withPivot('position')
            ->orderBy('competition_procedure_types.position');
    }

    public function procedureType()
    {
        return $this->procedureTypes()->first();
    }

    public function cpvs()
    {
        return $this->belongsToMany(Cpv::class, 'competition_cpvs');
    }

    public function watchlists()
    {
        return $this->belongsToMany(Watchlist::class, 'watchlist_competitions', 'competition_id', 'watchlist_id');
    }

    // Prevents loading all watchlists when accessing the relation if not eager loaded with user filter
    public function getWatchlistsAttribute()
    {
        return $this->relationLoaded('watchlists') ? $this->getRelationValue('watchlists') : collect();
    }

    public function nuts3Region()
    {
        return $this->belongsTo(Nuts3Region::class);
    }

    public function result()
    {
        return $this->hasOne(Result::class);
    }

    public function trackedResult()
    {
        return $this->hasOne(TrackedResult::class);
    }

    public function updatedCompetition()
    {
        return $this->belongsTo(Competition::class, 'updated_competition_id');
    }

    public function updatedByCompetitions()
    {
        return $this->hasMany(Competition::class, 'updated_competition_id');
    }

    public function images()
    {
        return $this->belongsToMany(MediaItem::class, 'competition_images');
    }

    public function documents()
    {
        return $this->belongsToMany(MediaItem::class, 'competition_documents');
    }
}
