<?php

namespace App\Models\Service;

use Carbon\Carbon;
use Illuminate\Support\Arr;
use Leenooks\Carbon as LeenooksCarbon;

/**
 * Class SSL (Service)
 * Services that are provide an SSL Certificate
 */
class SSL extends Type
{
	protected $table = 'service_ssl';

	protected $public_key = NULL;
	protected $crt_parse = NULL;

	public function __get($key): mixed
	{
		return match ($key) {
			'in_contract' => FALSE,

			default => parent::__get($key),
		};
	}

	/* STATIC METHODS */

	public static function boot()
	{
		parent::boot();

		static::retrieved(function($model) {
			if ($model->cert);
				$model->crt_parse = collect(openssl_x509_parse($model->cert));

			if ($model->csr) {
				$model->public_key = collect(openssl_pkey_get_details(openssl_csr_get_public_key($model->csr)));
			}
		});
	}

	/* INTERFACES */

	/**
	 * Return the Cert DN
	 *
	 * @return string
	 */
	public function getServiceDescriptionAttribute(): string
	{
		if ($this->cert)
			return Arr::get($this->crt_parse,'name');

		elseif ($this->csr) {
			$dn = '';
			$dna = openssl_csr_get_subject($this->csr);

			dump(['dna'=>$dna,'csr'=>$this->csr,'id',$this->id]);
			foreach ($dna as $k=>$v) {
				if ($dn)
					$dn .= ',';

				$dn .= sprintf('%s=%s',$k,$v);
			}

			return $dn;
		} else {
			return '[NO DN]';
		}
	}

	/**
	 * Return the Certificate Expiry Date
	 */
	public function getServiceExpireAttribute(): ?LeenooksCarbon
	{
		return $this->cert ? LeenooksCarbon::createFromTimestamp($this->crt_parse->get('validTo_time_t')) : NULL;
	}

	/**
	 * Return the Cert Name
	 *
	 * @return string
	 */
	public function getServiceNameAttribute(): string
	{
		return $this->cert
			? Arr::get($this->crt_parse,'subject.CN')
			: Arr::get(openssl_csr_get_subject($this->csr),'CN','');
	}
}