<?php

namespace App\Models\Service;

use Illuminate\Support\Arr;
use Carbon\Carbon;

use App\Interfaces\ServiceItem;
use App\Models\Base\ServiceType;
use App\Traits\NextKey;

class SSL extends ServiceType implements ServiceItem
{
	use NextKey;
	const RECORD_ID = 'service__ssl';

	protected $table = 'ab_service__ssl';

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

	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)));
			}
		});
	}

	public function getValidToAttribute()
	{
		return $this->cert ? Carbon::createFromTimestamp($this->crt_parse->get('validTo_time_t')) : NULL;
	}

	public function getServiceDescriptionAttribute(): string
	{
		if ($this->cert)
			return Arr::get($this->crt_parse,'name');

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

			foreach ($dna as $k=>$v) {
				if ($dn)
					$dn .= ',';

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

			return $dn;
		}
	}

	public function getServiceNameAttribute(): string
	{
		return $this->cert
			? Arr::get($this->crt_parse,'subject.CN')
			: Arr::get(openssl_csr_get_subject($this->csr),'CN');
	}

	public function inContract(): bool
	{
		// N/A
		return FALSE;
	}
}