<?php

namespace Vinteract\Auth;

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

use \Illuminate\Database\Eloquent\Model;

use DateTime;
use DateInterval;

class VerificationCode extends Model {
	
	public $timestamps = false;
	
    protected $table = "verification_codes";
	protected $connection = "default";
	protected $fillable = ["scope", "mobile_number", "code", "hash"];
	protected $visible = ["id", "mobile_number", "created"];
	
	protected static function boot() {
		
		parent::boot();
		
		static::setEventDispatcher(new \Illuminate\Events\Dispatcher());
		
		static::creating(function($model) {
			
			// Variables.
			
			$now = new DateTime();
			
			// Standard properties.
			
			$model->org_type = Client::getType();
			$model->org_id = Client::getId();
			$model->created = $now->format("Y-m-d H:i:s");
			
			// Generate code.
			
			$model->code = rand(100000, 999999);
			
			// Generate hash.
			
			$model->hash = Utils::generateHash($_SERVER["REMOTE_ADDR"]);
			
			// Generate expiry date.
			
			$expires = clone $now;
			$expires->add(new DateInterval("PT5M"));
			
			$model->expires = $expires->format("Y-m-d H:i:s");
			
		});
		
	}
	
	public function newQuery($excludeDeleted = true) {
		return parent::newQuery($excludeDeleted = true)
			->where("org_type", Client::getType())
			->where("org_id", Client::getId());
	}
	
	public function verify() {
		
		$hash = Utils::generateHash($_SERVER["REMOTE_ADDR"]);
		
		$now = new DateTime();
		$expires = new DateTime($this->expires);
		
		return (($hash === $this->hash) and ($now < $expires));
		
	}
	
	public function getFormattedMessage() {
		
		// Variables.
		
		$messages = [
			"cms:login" => "Your V interact verification code is {CODE}",
			"cms:add-new-user" => "Your V interact verification code is {CODE}",
			"v-pay:refund" => "Your {PAYMENT_PLATFORM_NAME} verification code is {CODE}",
			"v-pay:payment" => "Your {PAYMENT_PLATFORM_NAME} verification code is {CODE} to continue your payment to {CLIENT_NAME}",
		];
		
		$variables = [
			"{CODE}" => $this->code,
			"{CLIENT_NAME}" => \Vinteract\Client::getDisplayName(),
			"{PAYMENT_PLATFORM_NAME}" => \Vinteract\Payments\Payments::getName(),
		];
		
		// What message?
		
		$message = "Your V interact verification code is {CODE}";
		
		if (array_key_exists($this->scope, $messages)) {
			$message = $messages[$this->scope];
		}
		
		// Format message.
		
		foreach ($variables as $key => $value) {
			$message = str_replace($key, $value, $message);
		}
		
		return $message;
		
	}
	
	public function shouldSelfDestruct() {
		return $this->scope !== "cms:add-new-user";
	}
	
}