<?php

namespace App\Models;

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

use App\Traits\ProviderRef;

class Tax extends Model
{
	use ProviderRef;

	public $timestamps = FALSE;

	/* RELATIONS */

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

	public function providers()
	{
		return $this->belongsToMany(ProviderOauth::class,'tax__provider')
			->withPivot('ref','synctoken','created_at','updated_at');
	}

	/* METHODS */

	/**
	 * Calculate Tax on a value, and return that value with tax applied
	 *
	 * @param float $value
	 * @param Collection $taxes
	 * @return float
	 */
	public static function calc(float $value,Collection $taxes): float
	{
		$tax = 0;

		foreach ($taxes as $o) {
			// Quick sanity check
			if (! $o instanceof self)
				abort(500,'Invalid object for tax calculation');

			$tax += round($value*$o->rate,2);
		}

		return round($value+$tax,2);
	}
}