<?php

namespace Vinteract\Resources;

use \Vinteract\Client;

use \Illuminate\Database\Eloquent\Model;

class UserGroup extends Model {
	
	/*
		Properties
	*/
	
	public $timestamps = false;
	
	protected $hidden = ["pivot"];
	
	protected $visible = [
		"id",
		"uuid",
		"title",
		"body",
		//"image_url",
		//"image_source",
		//"display_position",
		"users",
		"type"
	];
	
	protected $fillable = [
		"uuid",
		"title",
		"body",
		"image_url",
		"image_source",
		"display_position",
		"public",
		"paid",
		"free",
		"followers",
		"visible",
	];
	
	/*
		Overrides
	*/
	
	public function __construct($attributes = []) {
		
		parent::__construct($attributes);
		
		$this->setTable(Client::getName() . "_user_groups");
		$this->setConnection(Client::getType());
		
	}
	
	protected static function boot() {
		
		parent::boot();
		
		static::setEventDispatcher(new \Illuminate\Events\Dispatcher());
		
		static::creating(function($model) {
			$model->uuid = \Vinteract\Utils::generateUuid();
		});
		
	}
	
	public function newQuery($excludeDeleted = true) {
		return parent::newQuery($excludeDeleted = true)
			->whereVisible(1)
			->select()
			->selectRaw("
				CASE WHEN public = 1 THEN 'Public'
				WHEN paid = 1 THEN 'Paid'
				WHEN free = 1 THEN 'Free'
				WHEN followers = 1 THEN 'Followers'
				WHEN public = 0 THEN 'Private'
				END AS type
			");
	}
	
	/*
		Scopes
	*/
	
	public function scopeIsPublic($query) {
		$query->where("public", 1)
			->where("paid", 0)
			->where("free", 0)
			->where("followers", 0)
			->where("visible", 1);
	}
	
	public function scopeIsPrivate($query) {
		$query->where("public", 0)
			->where("paid", 0)
			->where("free", 0)
			->where("followers", 0)
			->where("visible", 1);
	}
	
	public function scopeIsFollowers($query) {
		$query->where("public", 0)
			->where("paid", 0)
			->where("free", 0)
			->where("followers", 1)
			->where("visible", 1);
	}
	
	public function scopeMinimalInformation($query) {
		$query->select(["{$this->table}.id", "{$this->table}.title"]);
	}
	
	/*
		Relationships
	*/
	
	public function users() {
		
		$u = (Client::getName() . "_users");
		$ug = (Client::getName() . "_user_groups");
		$ugu = (Client::getName() . "_user_groups_users");
		
        return $this->belongsToMany("\Vinteract\Resources\User", $ugu);
		
    }
	
}