<?php

namespace Vinteract\Resources;

use \Vinteract\Client;

use \Illuminate\Database\Eloquent\Model;

use DateTime;

class SentNotification extends Model {
	
	/*
		Properties
	*/
	
	public $timestamps = false;
	
	protected $visible = [
		
		"id",
		"title",
		"body",
		"content_item",
		"to_who",
		"manual",
		"app",
		"web",
		"sms",
		"email",
		"user_groups",
		"users",
		"added",
		"system",
		
	];
	
	protected $fillable = [
		
		"title",
		"body",
		"content_type",
		"content_id",
		"to_who",
		"user_group",
		"organisation",
		"individuals",
		"manual",
		"app",
		"web",
		"sms",
		"email",
		"system",
		
	];
	
	protected $appends = [
		"content_item",
		"user_groups",
		"users",
	];
	
	protected $casts = [
		"manual" => "boolean",
		"app" => "boolean",
		"web" => "boolean",
		"sms" => "boolean",
		"email" => "boolean",
		"system" => "boolean",
	];
	
	/*
		Overrides
	*/
	
	public function __construct($attributes = []) {
		
		parent::__construct($attributes);
		
		$this->setTable(Client::getName() . "_notifications");
		$this->setConnection(Client::getType());
		
	}
	
	protected static function boot() {
		
		parent::boot();
		
		static::setEventDispatcher(new \Illuminate\Events\Dispatcher());
		
		static::creating(function($model) {
			$model->added = (new DateTime())->format("c");
		});
		
	}
	
	public function newQuery($excludeDeleted = true) {
		return parent::newQuery($excludeDeleted = true)
			->orderByDesc("id");
	}
	
	/*
		Mutators
	*/
	
	public function getContentItemAttribute() {
		try {
			if ($this->content_type !== "custom" and isset($this->content_id)) {
				$id = $this->content_id;
				$item = \Vinteract\Client::local($this->content_type)->select(["id", "title", "body"]);
				if ($id === "latest") {
					$item->latest("added");
				} elseif ($id === "soonest" and $type === "events") {
					$item->oldest("soonest_date");
				} else {
					$item->whereId($id);
				}
				return $item->first();
			}
		} catch (\Exception $e) {
			
		}
		return [];
	}
	
	public function getUserGroupsAttribute() {
		if (isset($this->user_group)) {
			return \Vinteract\Resources\UserGroup::find(json_decode($this->user_group, true));
		}
		return [];
	}
	
	public function getUsersAttribute() {
		if (isset($this->individuals)) {
			return \Vinteract\Resources\User::find(explode(",", $this->individuals));
		}
		return [];
	}
	
}