<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\ModelNotFoundException;

use App\Models\Supplier\{Broadband,Generic,Phone,Type};
use App\Traits\SiteID;

class SupplierDetail extends Model
{
	use SiteID;

	protected $casts = [ 'connections'=>'collection' ];

	/* RELATIONS */

	public function broadbands()
	{
		return $this->hasMany(Broadband::class);
	}

	public function generics()
	{
		return $this->hasMany(Generic::class);
	}

	public function phones()
	{
		return $this->hasMany(Phone::class);
	}

	public function supplier()
	{
		return $this->belongsTo(Supplier::class);
	}

	/* METHODS */

	/**
	 * Find a supplier product of a particular type
	 *
	 * @param string $type
	 * @param int $id
	 * @return Type
	 * @throws \Exception
	 */
	public function supplier_product(string $type,int $id): Type
	{
		switch ($type) {
			case 'broadband':
				$item =  $this->broadbands->where('id',$id);
				break;

			case 'phone':
				$item =  $this->phones->where('id',$id);
				break;

			default:
				throw new \Exception('Unknown type: '.$type);
		}

		if ($item->count() !== 1)
			throw new ModelNotFoundException(sprintf('Unknown Model of type [%s] with id [%d]',$type,$id));

		return $item->pop();
	}
}