<?php

namespace Vinteract\Resources;

use \Vinteract\Client;

use \Illuminate\Database\Eloquent\Model;

use DateTime;
use DateTimezone;
use DateInterval;

class QueuedNotification extends Model {
	
	/*
		Properties
	*/
	
	public $timestamps = false;
	
	protected $visible = [
		
		"id",
		"title",
		"body",
		"content_type",
		"content_id",
		"to",
		"occurrence",
		"start_date",
		"start_date_offset",
		"send_date",
		"send_date_offset",
		"custom_dates",
		"app",
		"web",
		"sms",
		
		"added",
		"added_by",
		"updated",
		"updated_by",
		
		"content_item",
		"user_groups",
		"users",
		
	];
	
	protected $fillable = [
		
		"title",
		"body",
		"content_type",
		"content_id",
		"to",
		"user_group",
		"organisation",
		"individuals",
		"occurrence",
		"start_date",
		"send_date",
		"custom_dates",
		"app",
		"web",
		"sms",
		
		"added",
		"added_by",
		"updated",
		"updated_by",
		
	];
	
	protected $appends = [
		"content_item",
		"user_groups",
		"users",
	];
	
	protected $casts = [
	    "custom_dates" => "array",
		"app" => "boolean",
		"web" => "boolean",
		"sms" => "boolean",
	];
	
	/*
		Overrides
	*/
	
	public function __construct($attributes = []) {
		
		parent::__construct($attributes);
		
		$this->setTable(Client::getName() . "_notifications_queue");
		$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");
			$model->updated = (new DateTime())->format("c");
		});
		
		static::updating(function($model) {
			$model->updated = (new DateTime())->format("c");
		});
		
	}
	
	public function newQuery($excludeDeleted = true) {
		return parent::newQuery($excludeDeleted = true)
			->select()
			->selectRaw("CONVERT_TZ(start_date, '+00:00', '" . \Vinteract\Client::getTimezoneOffset() . "') AS start_date_offset")
			->selectRaw("CONVERT_TZ(send_date, '+00:00', '" . \Vinteract\Client::getTimezoneOffset() . "') AS send_date_offset");
	}
	
	/*
		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 [];
	}
	
	/*
		Functions
	*/
	
	public function isCustomDateNotification() {
		return $this->occurrence === "Custom";
	}
	
	public function moveSendDateForward() {
		
		// Calculate new dates.
		
		$send_date = new DateTime($this->send_date, new DateTimezone("UTC"));
		
		if ($this->occurrence == "Daily") {
			$interval = new DateInterval("P1D");
		} elseif ($this->occurrence == "Weekly") {
			$interval = new DateInterval("P7D");
		} elseif ($this->occurrence == "Fortnightly") {
			$interval = new DateInterval("P14D");
		}
		
		$send_date->add($interval);
		
		// Update model.
		
		$this->send_date = $send_date->format("Y-m-d H:i:s");
		
		// Update database.
		
		return $this->save();
		
	}
	
	public function disableCustomDate() {
		
		if (count($this->custom_dates)) {
			
			$modifiedDates = $this->custom_dates;
			
			foreach ($modifiedDates as &$date) {
				if ($date["enabled"] === "true") {
					$date["enabled"] = "false";
				}
				break;
			}
			
			$this->custom_dates = $modifiedDates;
			
		}
		
		return $this->save();
		
	}
	
	public function readyToSend() {
		
		$todays_date = new DateTime("now");
		
		if ($this->occurrence === "Custom") {
			if (count($this->custom_dates)) {
				foreach ($this->custom_dates as $date) {
					if ($date["enabled"] === "true") {
						$send_date = new DateTime($date["day"]);
					}
					break;
				}
			}
		} else {
			$send_date = new DateTime($this->send_date);
		}
		
		if (isset($send_date)) {
			return $todays_date >= $send_date;
		}
		
		return false;
		
	}
	
}