<?php

/*
 * This file is part of the AuthStack project.
 *
 * (c) Buckhill Ltd <development@buckhill.co.uk>
 *
 * This source file is subject to the Buckhill license that is bundled
 * with this source code in the file LICENSE.
 */

namespace  AuthStack\TwoFactor\Model;

use AuthStack\TwoFactor\Model\Key;
use Illuminate\Database\Eloquent\Model;

class SecurityKey extends Model
{
    protected $table = 'view_user_security_keys';
    public $timestamps = true;
    protected $fillable = ['user_id', 'key_id', 'security_key', 'created_at', 'updated_at', 'deleted_at', 'used_at'];

    protected $casts = [
        'security_key' => 'array',
    ];

    protected $dates = [

    ];


    /**
     * @param $value
     */
    public function setSecurityKeyAttribute($value)
    {
        $this->attributes['security_key'] = json_encode($value, JSON_UNESCAPED_SLASHES);
    }

    /**
     * @return array
     */
    public function getSecurityKeyMetadata()
    {
        return $this->security_key;
    }

    /**
     * @return Key
     */
    public function toKey()
    {
        $data = array_merge($this->toArray(), ['is_u2f' => $this->getAttribute('mode_id') == MFAMode::MODE_U2F]);

        return Key::fromArray($data);
    }
}
