<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

use App\Traits\SiteID;

class ProviderOauth extends Model
{
	use SiteID;

	protected $table = 'provider_oauth';

	protected $fillable = ['name','active'];

	/* RELATIONS */

	public function accounts()
	{
		return $this->belongsToMany(Account::class,'account__provider')
			->where('account__provider.site_id',$this->site_id)
			->withPivot('ref','synctoken','created_at','updated_at');
	}

	public function invoices()
	{
		return $this->belongsToMany(Invoice::class,'invoice__provider')
			->where('invoice__provider.site_id',$this->site_id)
			->withPivot('ref','synctoken','created_at','updated_at');
	}

	public function payments()
	{
		return $this->belongsToMany(Payment::class,'payment__provider')
			->where('payment__provider.site_id',$this->site_id)
			->withPivot('ref','synctoken','created_at','updated_at');
	}

	public function taxes()
	{
		return $this->belongsToMany(Tax::class,'tax__provider')
			->where('tax__provider.site_id',$this->site_id)
			->withPivot('ref','synctoken','created_at','updated_at');
	}

	public function tokens()
	{
		return $this->hasMany(ProviderToken::class);
	}

	public function users()
	{
		return $this->hasMany(UserOauth::class);
	}

	/* METHODS */

	/**
	 * @return string|null
	 */
	public function api_class(): ?string
	{
		return config('services.provider.'.strtolower($this->name).'.api');
	}

	/**
	 * Return a list of the provider OAUTH details
	 */
	public static function providers(): Collection
	{
		return (new self)::whereIn('name',array_keys(config('services.provider')))->get();
	}

	/**
	 * Return the token object for a specific user
	 *
	 * @param User $uo
	 * @return ProviderToken|null
	 */
	public function token(User $uo): ?ProviderToken
	{
		return (($x=$this->tokens->where('user_id',$uo->id))->count() === 1) ? $x->pop() : NULL;
	}
}