<?php

namespace Vinteract\Resources;

use \Vinteract\Client;
use \Vinteract\Utils;

use \Illuminate\Database\Eloquent\Model;

class AuthenticationCode extends Model {
	
	public $timestamps = false;
	
	protected $connection = "default";
	protected $fillable = ["code", "content_type", "content_id"];
	protected $visible = ["code"];
	
	public function __construct($attributes = []) {
		
		parent::__construct($attributes);
		
		$this->setTable("global_" . Client::getType() . "_authentication_codes");
		
	}
	
	protected static function boot() {
		
		parent::boot();
		
		static::setEventDispatcher(new \Illuminate\Events\Dispatcher());
		
		static::creating(function($model) {
			$model->code = hash("sha256", mt_rand());
			$model->org_id = Client::getId();
		});
		
	}
	
	public function newQuery($excludeDeleted = true) {
		return parent::newQuery($excludeDeleted = true)
			->where("org_id", Client::getId());
	}
	
	public function getUrl() {
		if (Client::hasWebsite()) {
			return Client::getWebsiteURL("authenticate?code={$this->code}");
		}
		return Utils::getCmsURL("authenticate?code={$this->code}");
	}
	
}