<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

/**
 * This table is used to uniquely identify the website and database behind a URL.
 */
class Site extends Model
{
	use HasFactory;

	public $timestamps = FALSE;

	public function __get($key)
	{
		// If we already have a value, return it
		if ($x = parent::__get($key))
			return $x;

		// Get the value from the details table
		if (($x=$this->detail_item($key)) !== NULL)
			return $x;

		// Get a default value for this key
		if (($value = SiteDetail::sample($key)) === NULL)
			abort(500,sprintf('No default value for [%s]',$key));

		// At this point our DB doesnt have this value, we'll log an alert
		if ($this->exists)
			Log::alert(sprintf('Site [%d] is missing value for key [%s] - providing a default [%s]',$this->site_id,$key,serialize($value)));

		return $value;
	}

	/* RELATIONS */

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

	public function currency()
	{
		return $this->belongsTo(Currency::class);
	}

	public function details()
	{
		return $this->hasMany(SiteDetail::class,NULL,'site_id');
	}

	public function language()
	{
		return $this->belongsTo(Language::class);
	}

	public function taxes()
	{
		return $this->hasMany(Tax::class,'country_id','country_id');
	}

	/* ATTRIBUTES */

	/**
	 * Return the site address as an array
	 *
	 * @return array
	 */
	public function getAddressAttribute(): array
	{
		return [
			$this->site_address1,
			$this->site_address2,
			sprintf('%s %s  %s',$this->site_city.(($this->site_state OR $this->site_postcode) ? ',' : ''),$this->site_state,$this->site_postcode)
		];
	}

	/**
	 * Add the path to the mail logo, so it can be displayed.
	 *
	 * @return string
	 */
	public function getEmailLogoAttribute(): string
	{
		return (($x=$this->detail_item('email_logo')) !== NULL) ? '/storage/'.$x : '/image/generic/150/20/fff';
	}

	/**
	 * Add the path to the site logo, so it can be displayed.
	 *
	 * @param $value
	 * @return string
	 */
	public function getSiteLogoAttribute($value): string
	{
		return (($x=$this->detail_item('site_logo')) !== NULL) ? '/storage/'.$x : '/image/generic/150/20/fff';
	}

	/* METHODS */

	/**
	 * Get a key from the site_details
	 *
	 * @param $key
	 * @return mixed
	 */
	private function detail_item($key)
	{
		return (($x=$this->details->search(function($item) use ($key) { return $item->key === $key; })) !== FALSE)
			 ? $this->details->get($x)->value
			: NULL;
	}
}