<?php

namespace Vinteract\Analytics;

use \Vinteract\Client;

use \Illuminate\Database\Eloquent\Model;

class Event extends Model {
	
	/*
		Properties
	*/
	
	public $timestamps = false;
	
	//protected $with = ["installation"];
	
	//protected $fillable = ["type", "title", "body", "image_url", "amount", "minimum_amount", "pwyw"];
	//protected $visible = ["id", "public_id", "title", "body", "amount", "minimum_amount", "pwyw"];
	
	/*
		Overrides
	*/
	
	public function __construct($attributes = []) {
		
		parent::__construct($attributes);
		
		$this->setTable("global_" . Client::getType() . "_analytics_events");
		
	}
	
	public function newQuery($excludeDeleted = true) {
		return parent::newQuery($excludeDeleted = true)
			->where("environment", ENVIRONMENT === "development" ? "development" : "production")
			->where("org_id", Client::getId())
			->orderBy("id", "desc");
	}
	
	/*
		Functions
	*/
	
	public static function fetch($params = []) {
		
		// Get query.
		
		$query = self::query()->with(["installation"]);
		
		// Params / conditions?
		
		if ($params) {
			
			if (array_key_exists("from", $params)) {
				$query->whereDate("added", ">=", $params["from"]);
			}
			
			if (array_key_exists("to", $params)) {
				$query->whereDate("added", "<=", $params["to"]);
			}
			
			if (array_key_exists("limit", $params)) {
				$query->limit($params["limit"]);
			}
			
			if (array_key_exists("platform", $params)) {
				$query->whereHas("installation", function($i) use ($params) {
					$i->where("platform", "like", $params["platform"]);
				});
			}
			
		}
		
		// Get result.
		
		return $query->get();
		
	}
	
	/*
		Relationships
	*/
	
	public function installation() {
        return $this->belongsTo("\Vinteract\Analytics\Installation");
    }
	
}
