<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Leenooks\Traits\CompositeKeys;

use App\Traits\SiteID;

class SiteDetail extends Model
{
	use CompositeKeys,SiteID;

	protected $casts = [
		'social' => 'array',
		'top_menu' => 'array',
	];

	public $incrementing = false;
	protected $primaryKey = ['site_id','key'];

	/**
	 * Sample data to use with new sites, if there is no database record
	 */
	private const sampleData = [
		'country_id' => 61,
		'currency_id' => 6,
		'language_id' => 1,
		'site_id' => 0,
		'site_name' => 'MY OSB SITE',
		'site_description'=>'Example Site',
		'site_phone'=>'+0 1 2345 6789',
		'site_email' => 'nobody@example.com',
		'site_address1' => 'Address line 1',
		'site_address2' => 'Address line 2',
		'site_city' => 'City',
		'site_state' => 'State',
		'site_postcode' => '12345',
		'social'=>[
			['name'=>'facebook','url'=>'http://www.facebook.com'],
			['name'=>'linkedin','url'=>'http://www.linkedin.com'],
			['name'=>'twitter','url'=>'http://www.twitter.com'],
		],
		'top_menu'=>[
			'Home'=>['name'=>'Home','url'=>'/','children'=>[
				['name'=>'Link 1','url'=>'#/l2', 'children'=>[]],
				['name'=>'Link 2','url'=>'#/l2', 'children'=>[]],
			]],
			'Option1'=>['name'=>'Option 1','url'=>'/o1','children'=>[]],
			'Option2'=>['name'=>'Option 2','url'=>'/o2','children'=>[
				['name'=>'O2 Link 1','url'=>'#/o2l1', 'children'=>[]],
				['name'=>'O2 Link 1','url'=>'#/o2l2', 'children'=>[]],
			]],
		]
	];

	public $timestamps = FALSE;

	/* ATTRIBUTES */

	/**
	 * Enable us to cast some values
	 * @param $value
	 * @return void
	 */
	public function getValueAttribute($value)
	{
		switch(Arr::get($this->casts,$this->key)) {
			case 'array':
				return unserialize($value);
			default:
				return $value;
		}
	}

	/**
	 * Set our value, casting it if required
	 *
	 * @param $value
	 * @return void
	 * @throws \Exception
	 */
	public function setValueAttribute($value): void
	{
		// Check that the value can be set
		if (! $this->key)
			throw new \Exception('Please set key first');

		switch(Arr::get($this->casts,$this->key)) {
			case 'array':
				$value = serialize($value ?: []);
				break;
		}

		$this->attributes['value'] = $value;
	}

	/* METHODS */

	/**
	 * Get a sample key value
	 *
	 * @param $key
	 * @return mixed
	 * @throws \Exception
	 */
	public static function sample($key): mixed
	{
		return Arr::get(self::sampleData,$key);
	}
}